/******************************************************************************
*******************************************************************************

precisecontrol_JP.do

Authors: Dahyeon Jeong and Ajay Shenoy

Replication Codes for:

	"Can the Party in Power Systematically Win a Majority in Close Legislative Elections?"

*******************************************************************************
*******************************************************************************/


clear
cap cd "[PATH]" //Change to path of the analysis folder


//Labels
global redel 	"High-Stakes Election"
global nonel 	"Low-Stakes Election"

global redelsh 	"High-Stakes"
global nonelsh	"Low-Stakes"

global xlabmaj	`""Probability Democrats Won a" "Majority ({bf:Previous} Election)""'

global runlabdem `""Seats Won by Democrats ({bf:Current} Election)" "As % of total, relative to 50% threshold""'
global runlabmaj `""Seats Won in {bf:Current} Election" "by Party that {bf:Previously} Held Majority" "As % of total, relative to 50% threshold""'
global runlabinc `""Democratic Incumbents (Seats Won, {bf:Previous} Election)" "As % of total, relative to 50% threshold""'



cap mkdir "regressions"
cap mkdir "regressions/new"
cap mkdir "regressions/appendix"

cap mkdir "tables"
cap mkdir "tables/new"

cap mkdir "graphs"
cap mkdir "graphs/new"
cap mkdir "graphs/new/manipulate"
cap mkdir "graphs/new/appendix"
cap mkdir "graphs/new/appendix/revisions"
cap mkdir "graphs/new/appendix/sampdef"


/*******************************************************************************

					  Tables and Figures in the Main Text

*******************************************************************************/

/******************************
	Table 1: Main Results
******************************/
eststo clear

local bw 18
local out lagdemcon
local deg 1

use "dta/stateleg/partisan_balance_lh.dta", clear

//Alternative running variable: fraction of Republicans
gen rephs2		= 100 * ( hs_rep_elect- ceil(.5* hs_tot_elect) ) / hs_tot_elect

//Indicator: VRA Pre-Clearance State
gen vra = 0
foreach state in "Arizona" "Texas" "Louisiana" "Mississippi" "Alabama"  "Georgia"  "South Carolina" "Alaska" "Virginia" {
	replace vra = 1 if statename == "`state'"
}



keep if sample == 1

//Conditions for regressions
local cond1 ""													//Baseline
local cond2 "drop if (l.hs_ind_elect > 0 & l.hs_ind_elect < .) | (hs_ind_elect > 0 & hs_ind_elect < .)"	//Drop elections with independent legislators
local cond3 "drop if vra == 1"									//Drop VRA Pre-Clearance States
local cond4 ""													//Republican control running variable (same sample as others)

//Running Variables
local run1 demhs2
local run2 demhs2
local run3 demhs2
local run4 rephs2


foreach c in 1 2 3 4 {
	foreach redind in 0 1 {
		preserve
		
		`cond`c''
		
		local run `run`c''
		
		//Cluster (for standard errors)
		egen clust = group(year_redistrict state_id)

		//Indicator for control of the assembly
		gen control = (`run' >= 0) if !mi(`run')

		//Restrict to bandwidth
		keep if abs(`run') < `bw'

		//Generate control function
		forvalues p=1/`deg' {
			gen poly`p' = `run'^`p'
		}
		
		reg `out'  c.red_election##(c.poly* c.control c.control#c.poly*) , cluster(clust)
		test c.red_election#c.control
		local pvaleq = r(p)

		keep if red_election == `redind'

		//Run regression on micro data
		reg `out' poly* control c.control#c.poly* , cluster(clust)
		
		sum `out' if !control & abs(`run') < 5 & e(sample)
		estadd scalar conmean = r(mean)
		
		if `redind' == 1 {
			estadd scalar pvaleq = `pvaleq'
		}
		
		eststo
		
		restore
	}
}

// Make Table
tempfile out1 out2
#delimit;
esttab using `out1', booktabs label            
		b(3) se(3)  star(* 0.10 ** 0.05 *** 0.01) noobs keep(control) nonotes
		mgroups("Baseline" "No Ind. Leg." "Drop VRA States" "Republican Seats",
		pattern(1 0 1 0 1 0 1 0) prefix(\multicolumn{@span}{c}{) suffix(})   
        span erepeat(\cmidrule(lr){@span})) 
		sca("N  Observations" "N_clust Clusters" "conmean Control Mean" "pvaleq Test: Low=High") sfmt("%9.0g" "%9.0g" "%9.2f" "%9.2f")
		varlabel(control "Discontinuity") replace
		mtitle("${nonelsh}" "${redelsh}" "${nonelsh}" "${redelsh}" "${nonelsh}" "${redelsh}" "${nonelsh}" "${redelsh}")  
		;
#delimit cr

filefilter `out1' `out2', from("\BStoprule") to("\BStoprule\BStoprule")
filefilter `out2' "regressions/new/mainresults.tex", from("\BSbottomrule") to("\BSbottomrule\BSbottomrule") replace





/******************************
	Figure 2: Density Test
******************************/
local binsize 1
local title_0 "${nonel}"
local title_1 "${redel}"

graph drop _all
pause on
foreach eltype in 0 1 {
	use "dta/stateleg/partisan_balance_lh.dta", clear

	keep if sample == 1

	//It's not clear how to code the "incumbent" in these cases, so we drop them
	drop if (l.hs_ind_elect > 0 & l.hs_ind_elect < .) | (hs_ind_elect > 0 & hs_ind_elect < .)

	gen incshare = 100 * ( hs_dem_elect - ceil(.5* hs_tot_elect) ) / hs_tot_elect if lagdemcon == 1
	replace incshare = 100 * ( hs_rep_elect - ceil(.5* hs_tot_elect) ) / hs_tot_elect if lagdemcon == 0

	keep if red_elect == `eltype'
	
	preserve
	DCdensity incshare, breakpoint(0) generate(Xj Yj r0 fhat se_fhat) nograph b(`binsize')
	local est 	= string(r(theta),"%9.2f")
	local se 	= string(r(se),"%9.2f")
	local pval	= string(  2*( 1 - abs (   normal( r(theta) / r(se) )   ) ) , "%9.2f" )
	restore

	#delimit;
	DCdensity incshare, breakpoint(0) generate(Xj Yj r0 fhat se_fhat) b(`binsize')
					graphopt(`" 
					ylabel(0(.02).08, labsize(large) )
					graphregion(color(white))
					xtitle(${runlabmaj}, size(huge) )
					ytitle("Probability Density", size(huge) ) title("`title_`eltype''", size(huge) )
					text(.05 -29 "Log Difference:", size(vlarge) ) text(.05 -8 "`est'", size(vlarge)) 
					text(.045 -8 "(`se')", size(vlarge)) xlabel(-50(50)50, labsize(vlarge) )
					text(.078 -13 "Lose Control", color(gs10) size(large) )
					text(.078 15 "Retain Control", color(gs10) size(large) )
					name(g`eltype')
					"') 
					;
	#delimit cr
	
}


graph combine g0 g1, graphregion( color(white) fcolor(white) ) ysize(2.2)
graph drop g0 g1		
graph export "graphs/new/manipulate/mccrary.pdf", replace



/******************************
	Figure 3: Sorting Test
******************************/

local run demhs2
local bw 18
local out lagdemcon
local deg 1
local binsize 2

use "dta/stateleg/partisan_balance_lh.dta", clear



//Cluster (for standard errors)
egen clust = group(year_redistrict state_id)

//Indicator for control of the assembly
gen control = (`run' >= 0) if !mi(`run')

//Restrict to bandwidth
keep if abs(`run') < `bw'

//Generate control function
forvalues p=1/`deg' {
	gen poly`p' = `run'^`p'
}

keep if sample == 1

local title_0 "${nonel}"
local title_1 "${redel}"

cap graph drop  _all

pause off
foreach redind in 0 1 {
	preserve

	keep if red_election == `redind'

	//Run regression on micro data
	reg `out' poly* control c.control#c.poly* , cluster(clust)

	//Size of discontinuity and standard error
	local b 	= string( _b[control], "%9.3f" )
	local se 	= string( _se[control], "%9.3f" )

	//Round to construct bins
	gen bin = `run' - mod(`run',`binsize')
	replace bin = bin+`binsize'/2
	
	//Take bin averages (and counts)
	gen nonmi = e(sample)
	br `out' bin `run' statename election_year
	sort bin
	pause
	#d;
	twoway (hist bin, width(2) start(-18) xlabel(-17 -13 -9 -5 -1 1 5 9 13 17) freq)
	(scatteri 0 0 50 0, c(l) lp(-) lc(red) m(i)),
	graphregion(color(white))
	ytitle("Number of State-Election Years in Each Bin")
	xtitle("As % of total, relative to 50% threshold")
	ylabel(0(10)50)
	title(" `title_`redind'' ", size(vlarge) ) name(hist`redind')
	legend(off);
	#d cr
	pause
	
	collapse `out' (sum)nobs=nonmi, by(bin)

	pause
	//Recenter the running variable on the midpoints of the bins
	//gen `run' 					= bin+`binsize'/2
	gen `run' 					= bin
	gen control					= `run' > 0


	forvalues p=1/`deg' {
		gen poly`p' = `run'^`p'
	}
	predict pred

	#delimit;
	twoway 
	(scatteri 	-.02 -19 "Republican Control"
					-.02 1 "Democratic Control", ms(i) mlabsize(large) mlabcolor(gs10) )
	(scatter `out' `run' ${useweight}, msize(3) mc(navy) )				//Dots
	(line pred `run' if control)  				//Fit: Republican control
	(line pred `run' if !control) 				//Fit: Democratic control
	,
	text(.9 -14.5 "Discontinuity:", size(large) )  text(.9 -4 "`b'" "(`se')", size(large) ) 
	graphregion(color(white)) legend(off) 
	xtitle(${runlabdem}, size(vlarge) )
	ytitle(${xlabmaj}, size(vlarge) ) yscale( range(-0.05 1) ) ylabel(0 (.2) 1)
	title(" `title_`redind'' ", size(vlarge) ) name(g`redind') xline(0, lc(gs11) lp(dash) )
	;
	#delimit cr
	
	restore
}


graph combine g0 g1, graphregion(color(white) fcolor(white) ) ysize(3)
graph export "graphs/new/manipulate/incumbency.pdf", replace
graph drop g0 g1





/******************************************************
	Figure 4: Sorting Test (Robustness to Bandwidth)
******************************************************/

cap postclose rdest
tempfile rdest
postfile rdest bw b se nclust using `rdest'

foreach bw of numlist 22(-.5)4 {
	local run demhs2
	local out lagdemcon
	local deg 1



	use "dta/stateleg/partisan_balance_lh.dta", clear

	//Cluster (for standard errors)
	egen clust = group(year_redistrict state_id)

	//Indicator for control of the assembly
	gen control = (`run' >= 0) if !mi(`run')

	//Restrict to bandwidth
	keep if abs(`run') < `bw'

	//Generate control function
	forvalues p=1/`deg' {
		gen poly`p' = `run'^`p'
	}

	keep if sample == 1
	
	//keep if red_election == `redind'
	

	//Run regression on micro data
	//reg `out' poly* control c.control#c.poly* , cluster(clust)
	reg `out'  c.red_election##(c.poly* c.control c.control#c.poly*) , cluster(clust)
	
	local b 		= _b[c.red_election#c.control]
	local se		= _se[c.red_election#c.control]
	local nclust	= e(N_clust)
	
	post rdest (`bw') (`b') (`se') (`nclust')

	
}

postclose rdest

use `rdest', clear

gen bl = b - invt(nclust-1, .975)*se
gen bu = b + invt(nclust-1, .975)*se


gen bl2 = b - invt(nclust-1, .95)*se
gen bu2 = b + invt(nclust-1, .95)*se


local estcol gs8
local estcol2 gs12
#delimit;
scatter b bl bu bl2 bu2 bw, sort(bw) connect(direct direct direct direct direct) lp(solid dash dash shortdash shortdash) 
					lc(`estcol' `estcol2' `estcol2' `estcol' `estcol') mc(`estcol' `estcol2' `estcol2' `estcol' `estcol') 
					ms(O i i i i) msize(small) ylabel(-.5(.5)2, labsize(large) )
					xlabel(4(6)22, labsize(large))
					 yline(0, lc(black) ) 
					graphregion(color(white)) xtitle("Bandwidth", size(huge)) legend(off)
					text(1.8 20 "90% CI", color(`estcol') size(large)) text(1.6 20 "95% CI", color(`estcol2') size(large))
					ytitle("") title("Difference", size(huge)) name(g2)
					
		;
#delimit cr

local title_0 "${nonel}"
local title_1 "${redel}"

local ytit_0 ytitle("Discontinuity (90% and 95% CI) ", size(large))
local ytit_1 ytitle("")

foreach redind in 0 1 {
	cap postclose rdest
	tempfile rdest
	postfile rdest bw b se nclust using `rdest'

	foreach bw of numlist 22(-.5)4 {
		local run demhs2
		local out lagdemcon
		local deg 1



		use "dta/stateleg/partisan_balance_lh.dta", clear

		//Cluster (for standard errors)
		egen clust = group(year_redistrict state_id)

		//Indicator for control of the assembly
		gen control = (`run' >= 0) if !mi(`run')

		//Restrict to bandwidth
		keep if abs(`run') < `bw'

		//Generate control function
		forvalues p=1/`deg' {
			gen poly`p' = `run'^`p'
		}

		keep if sample == 1
		
		keep if red_election == `redind'

		//Run regression on micro data
		reg `out' poly* control c.control#c.poly* , cluster(clust)
		
		local b 		= _b[control]
		local se		= _se[control]
		local nclust	= e(N_clust)
		
		post rdest (`bw') (`b') (`se') (`nclust')

		
	}

	postclose rdest

	use `rdest', clear

	gen bl = b - invt(nclust-1, .975)*se
	gen bu = b + invt(nclust-1, .975)*se

	gen bl2 = b - invt(nclust-1, .95)*se
	gen bu2 = b + invt(nclust-1, .95)*se


	local estcol gs8
	local estcol2 gs12
	#delimit;
	scatter b bl bu bl2 bu2 bw, sort(bw) connect(direct direct direct direct direct) lp(solid dash dash shortdash shortdash) 
						lc(`estcol' `estcol2' `estcol2' `estcol' `estcol') mc(`estcol' `estcol2' `estcol2' `estcol' `estcol') 
						ms(O i i i i) msize(small) ylabel(-.5(.5)2, labsize(large) )
						xlabel(4(6)22, labsize(large))
						 yline(0, lc(black) ) 
						graphregion(color(white)) xtitle("Bandwidth", size(huge)) legend(off)
						`ytit_`redind'' title(" `title_`redind'' ", size(huge))  name(g`redind')
						
			;
	#delimit cr
}

graph combine g0 g1 g2, graphregion(color(white) fcolor(white) ) ysize(2) rows(1)
graph export "graphs/new/appendix/revisions/minor/3panel_bw.pdf", replace
graph drop g0 g1 g2





/******************************************************
	Figure 5: Comparison to Lee (2008)
******************************************************/

local run lagrv
local bw 5
local out democrat
local deg 1
local binsize .25

cap graph drop  _all


local run1 		lagrv
local out1 		democrat
local title1 	"Lee (2008) Finds an Incumbent Advantage..."
local xtitle1	`" "Votes for Democrat ({bf:Previous} Election)" "As % of total, relative to 50% threshold""'
local ytitle1	"Probability Democrat Wins ({bf:Current} Election)"

local run2 		rv
local out2 		lagdem
local title2 	"...but not Precise Control"
local xtitle2	`" "Votes for Democrat ({bf:Current} Election)" "As % of total, relative to 50% threshold" "'
local ytitle2	"Probability Democrat Won ({bf:Previous} Election)"

foreach spec in 1 2 {

	local run `run`spec''
	local out `out`spec''

	use "raw data/lee et al elections/enricoall2.dta" , clear
	gen lagrv = 100*(lagdemvoteshare-.5)
	gen lagdem = lagdemvoteshare > .5 if !mi(lagdemvoteshare )
	gen rv = 100*(demvoteshare - .5)
	
	drop if `run' == 0
	gen control = `run' > 0 if !mi(`run')

	//Restrict to bandwidth
	keep if abs(`run') < `bw'

	//Generate control function
	forvalues p=1/`deg' {
		gen poly`p' = `run'^`p'
	}



	reg `out' poly* control c.control#c.poly* , cluster(clusterid)
	//Size of discontinuity and standard error
	local b 	= string( _b[control], "%9.3f" )
	local se 	= string( _se[control], "%9.3f" )
	
	
	//Round to construct bins
	gen bin = `run' - mod(`run',`binsize')

	//Take bin averages (and counts)
	gen nonmi = e(sample)
	collapse `out' (sum)nobs=nonmi, by(bin)

	//Recenter the running variable on the midpoints of the bins
	gen `run' 					= bin+`binsize'/2
	gen control					= `run' > 0


	forvalues p=1/`deg' {
		gen poly`p' = `run'^`p'
	}
	predict pred

	#delimit;
	twoway 
	(scatteri 	.05 -3.9 "Republican Wins"
					.05 .05 "Democratic Wins", ms(i) mlabsize(large) mlabcolor(gs10) )
	(scatter `out' `run' ${useweight}, msize(3) mc(navy) )				//Dots
	(line pred `run' if control)  				//Fit: Republican control
	(line pred `run' if !control) 				//Fit: Democratic control
	,
	text(.9 -3.5 "Discontinuity:", size(large) )  text(.9 -1 "`b'" "(`se')", size(large) ) 
	graphregion(color(white)) legend(off) 
	xtitle(`xtitle`spec'', size(vlarge) )
	ytitle("`ytitle`spec''", size(vlarge) ) //ylabel(0 (.2) 1)
	title("`title`spec''", size(vlarge) ) name(g`spec') xline(0, lc(gs11) lp(dash) )
	ylabel(0(.25)1)
	;
	#delimit cr
}

graph combine g1 g2, graphregion(color(white) fcolor(white) ) ysize(3)
graph export "graphs/new/manipulate/comparison_to_lee2008.pdf", replace
graph drop g1 g2







/******************************************************
	Figure 6: No Incumbent Party Advantage
******************************************************/
local run lagdemhs2
local out demcon
local deg 1


local sc18 .8
local sc10 .7
local sc6  .6

local bsize18 	2
local bsize10 	1.5
local bsize6 	1

cap graph drop  _all


foreach bw in 18 10 6 {
	use "dta/stateleg/partisan_balance_lh.dta", clear

	local binsize = `bsize`bw''

	//Cluster (for standard errors)
	egen clust = group(year_redistrict state_id)

	//Indicator for control of the assembly
	gen control = (`run' >= 0) if !mi(`run')

	//Restrict to bandwidth
	keep if abs(`run') < `bw'

	//Generate control function
	forvalues p=1/`deg' {
		gen poly`p' = `run'^`p'
	}

	keep if sample == 1

	local title_0 "${nonel}"
	local title_1 "${redel}"


	foreach redind in 1 {
		preserve

		keep if red_election == `redind'

		//Run regression on micro data
		reg `out' poly* control c.control#c.poly* , cluster(clust)

		//Size of discontinuity and standard error
		local b 	= string( _b[control], "%9.3f" )
		local se 	= string( _se[control], "%9.3f" )

		//Round to construct bins
		gen bin = `run' - mod(`run',`binsize')

		//Take bin averages (and counts)
		gen nonmi = e(sample)
		collapse `out' (sum)nobs=nonmi, by(bin)

		//Recenter the running variable on the midpoints of the bins
		gen `run' 					= bin+`binsize'/2
		gen control					= `run' > 0


		forvalues p=1/`deg' {
			gen poly`p' = `run'^`p'
		}
		predict pred

		#delimit;
		twoway 
		//(scatteri 	-.02 -19 "Republican Control"
		//				-.02 1 "Democratic Control", ms(i) mlabsize(large) mlabcolor(gs10) )
		(scatter `out' `run' ${useweight}, msize(3) mc(navy) )				//Dots
		(line pred `run' if control)  				//Fit: Republican control
		(line pred `run' if !control) 				//Fit: Democratic control
		,
		text(.9 -`=`bw'*`sc`bw''' "Discontinuity:", size(large) )  text(.9 -`=`bw'*.2' "`b'" "(`se')", size(large) ) 
		graphregion(color(white)) legend(off) 
		xtitle("Seats Won by Democrats ({bf:Previous} Election)" "As % of total, relative to 50% threshold", size(vlarge) )
		ytitle("Probability Democrats Win a" "Majority ({bf:Current} Election)", size(vlarge) ) yscale( range(-0.05 1) ) ylabel(0 (.2) 1)
		title("Bandwidth = `bw' ", size(vlarge) ) name(g`bw') xline(0, lc(gs11) lp(dash) )
		;
		#delimit cr
		
		restore
	}

}

graph combine g18 g10 g6, graphregion(color(white) fcolor(white) ) ysize(2) rows(1)
graph export "graphs/new/manipulate/incumbency_figs.pdf", replace
graph drop g18 g10 g6







/******************************************************
	Figure 7: Hold Just Enough Seats to Retain Control
******************************************************/

use "dta/stateleg/partisan_balance_lh.dta", clear

keep if sample == 1

gen deltashare = demhs2 - lagdemhs2



/*
Losses when democrats are incumbents: margin of incumbency < 5
*/
twoway (hist deltashare if lagdemcon==1 & abs(lagdemhs) < 5 & !red_elect & abs(demhs2) < 18, fc(gs11) lc(gs12) start(-25) width(2.5) fraction) ///
		(hist deltashare if lagdemcon & abs(lagdemhs) < 5 & red_elect & abs(demhs2) < 18, fc(none) lw(medthick) lc(black) start(-25) width(2.5) fraction), ///
		legend(off) graphregion(color(white)) xtitle("Change in Democratic Seats, Percentage points of total", size(huge) ) name(g0) ytitle("Fraction", size(huge)) ///
		title("Democratic Incumbent Majority < 5% of Total", size(huge)) xlabel(-30(5)15, labsize(vlarge)) ylabel(0(.1).5, labsize(large) )


/*
Losses when democrats are incumbents: 5 =< margin of incumbency < 10
*/
twoway (hist deltashare if lagdemcon==1 & abs(lagdemhs) >= 5 & abs(lagdemhs) < 10 & !red_elect & abs(demhs2) < 18, fc(gs11) lc(gs12) width(2.5) start(-25) fraction ) ///
		(hist deltashare if lagdemcon & abs(lagdemhs) >= 5 & abs(lagdemhs) < 10 & red_elect & abs(demhs2) < 18, fc(none) lc(black) lw(medthick)  width(2.5) start(-25) fraction ), ///
		legend(off) graphregion(color(white)) xtitle("Change in Democratic Seats, Percentage points of total", size(huge) ) name(g1) ytitle("Fraction", size(huge)) ///
		text(.15 -15 "${nonel}", color(gs8) size(vlarge) ) text(.43 5 "${redel}", color(black) size(vlarge) ) ///
		title("5% <= Democratic Incumbent Majority < 10%", size(huge)) xlabel(-30(5)15, labsize(vlarge)) ylabel(0(.1).5, labsize(large) )
		
graph combine g0 g1, graphregion(color(white) fcolor(white) ) ysize(2)
graph export "graphs/new/manipulate/seatloss_bimodality.pdf", replace
graph drop g0 g1

				
				
				

				
				
				

/******************************************************
	Figure 8: Incumbent Exit Rate
******************************************************/

local window 18
local bw 3
local deg 1
local run lagdemhs2


use "dta/stateleg/compete_lh.dta", clear

//Outcome: indicator for whether a sitting lower house legislator does not compete
gen inc_exit		= (1 - competed_lh) if holdoffice_lh

keep if sample == 1



/*
Restrict to republicans only, democrats only, and neither party (independents/fusion)
*/
local cond1 republican==1
local cond2 democrat==1

local title1 "Republicans"
local title2 "Democrats"

local yt1		"Incumbent Exit Rate"

local ys1		"ylabel(.15(.05).35)"
local ys2		"ylabel(.15(.05).35)"


local legenda2 (scatteri .34 5 "" .34 7 "${redel}", connect(direct) lp(solid) lc(black) ms(i) mlabcolor(black) lw(medthick) mlabsize(medlarge) ) 
local legendb2 (scatteri .325 5 "" .325 7 "${nonel}", connect(direct) lp(solid) lc(gs8) ms(i) mlabcolor(gs8) lw(medthick) mlabsize(medlarge) ) 
foreach c in 1 2  {
	preserve
	local partyrest `cond`c''
	
	
	
	lpoly inc_exit `run' if abs(`run') < `window' & red_elect == 1 & (`partyrest'), deg(`deg') bw(`bw') gen(redx redy) se(redse) nograph
	lpoly inc_exit `run' if abs(`run') < `window' & red_elect == 0 & (`partyrest'), deg(`deg') bw(`bw') gen(nonx nony) se(nonse) nograph
	
	foreach type in red non {
		gen `type'y_u = `type'y + invnormal(.975)*`type'se
		gen `type'y_l = `type'y - invnormal(.975)*`type'se
	}
	
	#delimit;
	twoway 	(scatter redy redy_u redy_l redx, 
			connect(direct direct direct) lp(solid dash dash) lc(gs0 gs2 gs2) ms(i i i) lw(medthick medium medium) ) 
			
			(scatter nony nony_u nony_l nonx, 
			connect(direct direct direct) lp(solid dash dash) lc(gs8 gs11 gs11 ) ms(i i i) lw(medthick medium medium) ) 
			
			`legenda`c''
			`legendb`c''
			,
			legend(off) graphregion(color(white)) title("`title`c''", size(huge) ) name(g`c') ytitle("`yt`c''", size(huge) ) `ys`c''
			xtitle(${runlabinc}, size(huge)  )  xlabel(, labsize(vlarge) )
			;
	#delimit cr
	
	restore
}


graph combine g1 g2 , graphregion( color(white) fcolor(white) ) ysize(2) rows(1)
graph export "graphs/new/manipulate/exit_lpoly_ci.pdf", replace

graph drop g1 g2







/******************************************************
	Figure 9: Campaign Contributions
******************************************************/
use "dta/stateleg/partisan_balance_lh.dta", clear


merge m:1 statename using "dta/statecode_crosswalk.dta"
drop if _m != 3
drop _m

merge 1:1 stateabbrev election_year using "dta/stateleg/totalfunds_lh.dta"

keep if sample == 1



local window 10
local bw 1
local deg 1
local run lagdemhs2
local out totalreceipts

/*
Restrict to republicans only, democrats only, and neither party (independents/fusion)
*/
local cond1 rep
local cond2 dem
local cond3 !(republican==1 | democrat==1)

local title1 "Republicans"
local title2 "Democrats"
local title3 "Neither"

local yt1		"Total Receipts to Lower House" "State Legislators"

local ys1		"ylabel(0(5000000)10000000, labsize(vlarge) )"
local ys2		"ylabel(0(5000000)10000000, labsize(vlarge) )"
local ys3		"ylabel(0(.05).4)"

//mlabsize(small)
local legenda2 (scatteri 8200000 3 "" 8200000 5 "${redel}", connect(direct) lp(solid) lc(black) ms(i) mlabcolor(black) mlabsize(vlarge)  ) 
local legendb2 (scatteri 7500000 3 "" 7500000 5 "${nonel}", connect(direct) lp(dash) lc(gs8) ms(i) mlabcolor(gs8) mlabsize(vlarge)  ) 
foreach c in 1 2  {


	#delimit;
	twoway 	(lpoly `out'_`cond`c'' `run' if abs(`run') < `window' & red_elect == 1 , deg(`deg') bw(`bw') lp(solid) lc(black) ) 
			(lpoly `out'_`cond`c'' `run' if abs(`run') < `window' & red_elect == 0 , deg(`deg') bw(`bw') lp(dash)  lc(gs8) )
			`legenda`c''
			`legendb`c''
			,
			legend(off) graphregion(color(white)) title("`title`c''", size(huge) ) name(g`c') ytitle("`yt`c''" , size(huge) ) 
			xtitle(${runlabinc} , size(huge) ) `ys`c'' xlabel(, labsize(vlarge) )
			;
	#delimit cr
}

graph combine g1 g2 , graphregion( color(white) fcolor(white) ) ysize(2) rows(1)
graph export "graphs/new/manipulate/finance_lpoly.pdf", replace
graph drop g1 g2 







/******************************************************
	Figure 10: Campaign Contributions to Incumbents
******************************************************/
use "dta/stateleg/partisan_balance_lh.dta", clear


merge m:1 statename using "dta/statecode_crosswalk.dta"
drop if _m != 3
drop _m

merge 1:m stateabbrev election_year using "dta/stateleg/candidate_funds_lh.dta"
keep if _m == 3
keep if sample == 1

gen dem = party == "100"

/***********
Contributions to incumbents by margin of incumbency
***********/
foreach d in 1{

	local out totalpccontribs
	local run lagdemhs2
	local deg 1
	local bw 18
	local binsize 4

	local title_0 "${nonel}"
	local title_1 "${redel}"


	foreach redind in 0 1 {
		preserve

		keep if dem == `d' & incumchall == "I" & red_elect == `redind'


		//Cluster (for standard errors)
		egen clust = group(year_redistrict state_id)

		//Indicator for control of the assembly
		gen control = (`run' >= 0) if !mi(`run')

		//Restrict to bandwidth
		keep if abs(`run') < `bw'

		//Generate control function
		forvalues p=1/`deg' {
			gen poly`p' = `run'^`p'
		}



		//Run regression on micro data
		reg `out' poly* control c.control#c.poly* , cluster(clust)

		//Size of discontinuity and standard error
		local b 	= string( _b[control], "%9.3f" )
		local se 	= string( _se[control], "%9.3f" )

		//Round to construct bins
		gen bin = `run' - mod(`run',`binsize')

		//Take bin averages (and counts)
		gen nonmi = e(sample)
		collapse `out' (sum)nobs=nonmi, by(bin)

		//Recenter the running variable on the midpoints of the bins
		gen `run' 					= bin+`binsize'/2
		gen control					= `run' > 0


		forvalues p=1/`deg' {
			gen poly`p' = `run'^`p'
		}
		predict pred


		#delimit;
		twoway 
		(scatteri 	25000 -11.5 "Republican Control"
						25000 1 "Democratic Control", ms(i) mlabsize(large) mlabcolor(gs10) )
		(scatter `out' `run' ${useweight}, msize(3) mc(navy) )				//Dots
		(line pred `run' if control)  				//Fit: Republican control
		(line pred `run' if !control) 				//Fit: Democratic control
		,
		text(20000 -12 "Discontinuity:", size(vlarge) )  text(20000 -4 "`b'" "(`se')", size(vlarge) ) 
		graphregion(color(white)) legend(off) 
		xtitle(${runlabinc} , size(huge) ) xlabel(, labsize(vlarge)  )
		ytitle("Party Committee Contributions", size(huge) )  ylabel(0 (5000) 25000, labsize(vlarge) )
		title(" `title_`redind'' ", size(huge) ) xline(0, lc(gs11) lp(dash) ) name(g`redind') 
		;
		#delimit cr

		restore
	}

	graph combine g0 g1, graphregion(color(white) fcolor(white) ) ysize(2)
	graph export "graphs/new/manipulate/incumbent_fin`d'.pdf", replace
	graph drop g0 g1
	
	

}







/*******************************************************************************

					  Tables and Figures in the Appendices

*******************************************************************************/

/******************************************************
	Table A1: 
******************************************************/
local keylist ""

local run demhs2
local bw 18
local out lagdemcon
local deg 1
local binsize 2

use "dta/stateleg/partisan_balance_lh.dta", clear

//Presidential elections
gen presel = 0
foreach yr of numlist 1964(4)2012 {
	replace presel = 1 if election_year == `yr'
}

//Democrats retain majority
gen demmaj = (demcon == 1) if lagdemcon == 1 & !mi(demcon)
gen demmin = (demcon == 0) if lagdemcon == 0 & !mi(demcon)


//Cluster (for standard errors)
egen clust = group(year_redistrict state_id)

//Indicator for control of the assembly
gen control = (`run' >= 0) if !mi(`run')

//Restrict to bandwidth
//keep if abs(`run') < `bw'

//Generate control function
forvalues p=1/`deg' {
	gen poly`p' = `run'^`p'
}

keep if sample == 1

local title_0 "${nonel}"
local title_1 "${redel}"

cap graph drop  _all

foreach redind in 0 1 {
	preserve

	keep if red_election == `redind'

	/*
	Restrict to estimation sample
	*/
	reg `out' poly* control c.control#c.poly* , cluster(clust)
	
	keep if e(sample)
	
	foreach var of varlist demcon lagdemcon demhs2 presel demmaj demmin {
		sum `var'
		local `var'`redind' = string( `=r(mean)', "%9.2f" )
		
		local keylist "`keylist' `var'`redind'"
	}
	
	local n`redind' = string( `=e(N)', "%9.0g")
	local c`redind' = string( `=e(N_clust)', "%9.0g")
	
	local keylist "`keylist' n`redind' c`redind'"
	
	//Retain sample
	keep state_id election_year statename
	duplicates drop
	
	tempfile samp`redind'
	save `samp`redind''
	
	restore
}

/****************
Campaign Finance
*****************/

foreach redind in 0 1 {
	use `samp`redind'', clear


	merge m:1 statename using "dta/statecode_crosswalk.dta"
	drop if _m != 3
	drop _m

	merge 1:m stateabbrev election_year using "dta/stateleg/candidate_funds_lh.dta"
	keep if _m == 3
	
	foreach var of varlist totalpccontribs totalreceipts {
		sum `var'
		local `var'`redind' = string(  `=r(mean)', "%9.0f")
		
		local keylist "`keylist' `var'`redind'"
	}
}

	
/**************************
Incumbent Re-Election Rate
***************************/

use "dta/stateleg/compete_lh.dta", clear

//Outcome: indicator for whether a sitting lower house legislator does not compete
gen inc_exit		= (1 - competed_lh) if holdoffice_lh

keep if sample == 1


foreach redind in 0 1 {
	preserve
	keep if red_election == `redind'
	
	gen election_year = year
	merge m:1 election_year state_id using `samp`redind''
	keep if _m == 3
	
	gen increl = winner==1 if holdoffice_lh==1 & competed_lh==1 & !mi(winner)
	
	sum increl
	local increl`redind' = string( `=r(mean)', "%9.2f")
	
	local keylist "`keylist' increl`redind'"
	
	restore
}


	
// Output table using template
	//Base file:
	tempfile desc0
	filefilter "templates/descriptives.txt" "`desc0'", from(" ") to(" ")
	
	//Loop
	local onfile = 0
	foreach key in `keylist' {
		local tmp = `onfile'+1
		tempfile desc`tmp'
		filefilter "`desc`onfile''" "`desc`tmp''", from("[`key']") to("``key''")
		local onfile = `tmp'
	}
	
	//The last temporary file we made is the final version
	copy "`desc`tmp''" "tables/new/descriptives.tex", replace







/******************************************************
	Table A2: 
******************************************************/

eststo clear

/*********
Precise control prior to redistricting era?
**********/

local out lagdemcon
local run demhs2
local deg 1
local binsize 2

local redind 1
use "dta/stateleg/partisan_balance_lh_placebo.dta", clear


foreach bw in 18 10 {
	
	preserve
	
	//Cluster (for standard errors)
	egen clust = group(year_redistrict state_id)

	//Indicator for control of the assembly
	gen control = (`run' >= 0) if !mi(`run')

	//Restrict to bandwidth
	keep if abs(`run') < `bw'

	//Generate control function
	forvalues p=1/`deg' {
		gen poly`p' = `run'^`p'
	}

	keep if red_election == `redind'

	//Run regression on micro data
	reg `out' poly* control c.control#c.poly* , cluster(clust)
	
	sum `out' if !control & abs(`run') < 5 & e(sample)
	estadd scalar conmean = r(mean)
	eststo
	
	restore
	
}


tempfile out1 out2
#delimit;
esttab using `out1', booktabs label            
		b(3) se(3)  star(* 0.10 ** 0.05 *** 0.01) noobs keep(control) nonotes
		mgroups( "Pre-Redistricting" ,
		pattern(1 0 ) prefix(\multicolumn{@span}{c}{) suffix(})   
        span erepeat(\cmidrule(lr){@span})) 
		sca("N  Observations" "N_clust Clusters" "conmean Control Mean") sfmt("%9.0g" "%9.0g" "%9.2f")
		varlabel(control "Discontinuity") replace
		mtitle("$ BW = 18$ " "$ BW = 10$ ")  
		;
#delimit cr

filefilter `out1' `out2', from("\BStoprule") to("\BStoprule\BStoprule")
filefilter `out2' "regressions/appendix/interpretation.tex", from("\BSbottomrule") to("\BSbottomrule\BSbottomrule") replace





/******************************************************
	Table A3: 
******************************************************/
// Leads and lags: How important is the bianary high- versus low-stakes designation?
local out lagdemcon
local run demhs2
local deg 1
local binsize 2

local redind 1
use "dta/stateleg/partisan_balance_lh.dta", clear

eststo clear
foreach lead in 0 1 2 3 {
	foreach bw in 18 10 {
	
		preserve
		
		keep if sample == 1
		
		//Cluster (for standard errors)
		egen clust = group(year_redistrict state_id)

		//Indicator for control of the assembly
		gen control = (`run' >= 0) if !mi(`run')

		//Restrict to bandwidth
		keep if abs(`run') < `bw'

		//Generate control function
		forvalues p=1/`deg' {
			gen poly`p' = `run'^`p'
		}

		keep if f`lead'.red_election == `redind'

		//Run regression on micro data
		reg `out' poly* control c.control#c.poly* , cluster(clust)
		
		sum `out' if !control & abs(`run') < 5 & e(sample)
		estadd scalar conmean = r(mean)
		eststo
		
		restore
	}
}


tempfile out1 out2
#delimit;
esttab using `out1', booktabs label            
		b(3) se(3)  star(* 0.10 ** 0.05 *** 0.01) noobs keep(control) nonotes
		mgroups("Lead: 0" "Lead: 1" "Lead: 2" "Lead: 3" ,
		pattern(1 0 1 0 1 0 1 0 ) prefix(\multicolumn{@span}{c}{) suffix(})   
        span erepeat(\cmidrule(lr){@span})) 
		sca("N  Observations" "N_clust Clusters" "conmean Control Mean") sfmt("%9.0g" "%9.0g" "%9.2f")
		varlabel(control "Discontinuity") replace
		mtitle("$ BW = 18$ " "$ BW = 10$ " "$ BW = 18$ " "$ BW = 10$ " "$ BW = 18$ " "$ BW = 10$ " "$ BW = 18$ " "$ BW = 10$ ")  
		;
#delimit cr

filefilter `out1' `out2', from("\BStoprule") to("\BStoprule\BStoprule")
filefilter `out2' "regressions/appendix/leadstakes.tex", from("\BSbottomrule") to("\BSbottomrule\BSbottomrule") replace




/******************************************************
	Table A4: 
******************************************************/

local bw 18
local out lagdemcon
local deg 1
local binsize 2
local run demhs2

use "dta/stateleg/partisan_balance_lh.dta", clear


keep if sample == 1




eststo clear
foreach center of numlist 1971(10)2011 {

	preserve
	
	keep if abs(year_red-`center') <= 10
	
	//Cluster (for standard errors)
	egen clust = group(year_redistrict state_id)

	//Indicator for control of the assembly
	gen control = (`run' >= 0) if !mi(`run')

	//Restrict to bandwidth
	keep if abs(`run') < `bw'

	//Generate control function
	forvalues p=1/`deg' {
		gen poly`p' = `run'^`p'
	}

	keep if red_election == 1

	//Run regression on micro data
	reg `out' poly* control c.control#c.poly* , cluster(clust)
	
	sum `out' if !control & abs(`run') < 5 & e(sample)
	estadd scalar conmean = r(mean)
	eststo
	
	restore
	
}

#delimit;
esttab , 
		b(3) se(3)  star(* 0.10 ** 0.05 *** 0.01) noobs keep(control) nonotes
		sca("N  Observations" "N_clust Clusters" "conmean Control Mean") sfmt("%9.0g" "%9.0g" "%9.2f")
		varlabel(control "RD Estimate") replace
		mtitle("1971-1981" "1971-1991" "1981-2001" "1991-2011" "2001-2011" )  
		;
#delimit cr

#delimit;
esttab using "regressions/appendix/rolling.tex", 
		b(3) se(3)  star(* 0.10 ** 0.05 *** 0.01) noobs keep(control) nonotes
		sca("N  Observations" "N_clust Clusters" "conmean Control Mean") sfmt("%9.0g" "%9.0g" "%9.2f")
		varlabel(control "Discontinuity") replace
		mtitle("1971-1981" "1971-1991" "1981-2001" "1991-2011" "2001-2011" )  
		;
#delimit cr






/******************************************************
	Figure A1: 
******************************************************/

/*********
Get number of democrats and republicans actually in session (as opposed to
elected)
**********/

use "dta/state_legislature_detail.dta", clear
keep if year == 2011
keep statename hs_dem_in_sess hs_rep_in_sess

tempfile insess
save `insess'

/*********
Get running variable and representatives in session
**********/

use "dta/stateleg/partisan_balance_lh.dta", clear
keep if red_election


keep if year_redistrict == 2011
rename year sess_year

keep statename demhs2 //hs_dem_in_sess hs_rep_in_sess hs_ind_in_sess hs_vac_in_sess hs_tot_in_sess sess_year
tempfile run2
save `run2'



/*********
Get votes for most recent redistricting
**********/

import excel using "raw data/voting/voting_redistrict_20151009.xlsx", first clear


rename year year_redistrict
sort statename year_redistrict bill

#delimit ;
destring hs_dem_no hs_dem_yes hs_ind_no hs_ind_yes hs_rep_no hs_rep_yes sen_dem_no 
sen_dem_yes sen_ind_no sen_ind_yes sen_rep_no sen_rep_yes con_sen_dem_no con_sen_dem_yes 
con_sen_ind_no con_sen_ind_yes con_sen_rep_no con_sen_rep_yes con_hs_dem_no 
con_hs_dem_yes con_hs_ind_no con_hs_ind_yes con_hs_rep_no con_hs_rep_yes hs_tot_no 
hs_tot_yes sen_tot_no sen_tot_yes con_hs_tot_no, replace;
#delimit cr

keep if year == 2011

merge m:1 statename using `insess'
drop if _m==2
drop _m



merge m:1 statename using `run2'
drop if _m==2

//keep if sess_year == 2011

//Fraction of republicans or democrats who vote yes in house
//Note this is as a fraction actually in session, not those elected
gen fracrep = hs_rep_yes/ hs_rep_in_sess * 100
gen fracdem = hs_dem_yes/ hs_dem_in_sess * 100


#delimit ;
binplot fracdem, x(demhs2) bw(4) lineone linebreak 
			opt(`"
			legend(off) 
			xtitle(${runlabdem}, size(large) ) 
			ytitle("Percentage Voting Yes in Assembly", size(large) )
			title("Democrats", size(vlarge) ) name(g1)
			"')
			;
binplot fracrep, x(demhs2) bw(4) lineone linebreak 
			opt(`"
			legend(off) 
			xtitle(${runlabdem}, size(large) ) 
			ytitle("") 
			title("Republicans", size(vlarge) ) name(g2)
			"')
			;
#delimit cr

graph combine g1 g2, graphregion(color(white) fcolor(white)) ysize(3)
graph export "graphs/new/appendix/partylines.pdf", replace
graph drop g1 g2





/******************************************************
	Figure A2:
******************************************************/

use "dta/stateleg/partisan_balance_lh.dta", clear

local title0 "${nonel}"
local title1 "${redel}"

local legend legend(off)

//Bar graphs don't allow xlines, so we'll do a low-tech dashed line using text
//The second number in the loop is the number of dashes we want
local dashes ""
forvalues i=1/49 {
	local dashes "`dashes'- "
}

local cutoff 5

foreach r in 0 1 {
	preserve

	keep if sample == 1
	
	//It's not clear how to code the "incumbent" in these cases, so we drop them
	drop if (l.hs_ind_elect > 0 & l.hs_ind_elect < .) | (hs_ind_elect > 0 & hs_ind_elect < .)

	keep if red_elect == `r'
	

	
	egen dest 	= cut(demhs2) if !mi(demhs2) & !mi(lagdemhs2), at(-18 -10(5)10 18)

	
	label define dest -18 "[-18,-10)" -10 "[-10,-5)" -5 "[-5,0)" 0 "[0,5)" 5 "[5,10)" 10 "[10,18)"
	label values dest dest
	

	gen demgainseats = demhs > lagdemhs + `cutoff'		if !mi(lagdemhs)


	
	keep if abs(demhs2) < 18
	
	
	#delimit ;
	graph bar demgainseats , 
						over(dest, label(labsize(vlarge)) ) stack graphregion(color(white)) name(g`r') ylabel(0(.1).3) 
						bar(1, color(blue))  
						title("`title`r''", size(huge) )	`legend' 
						text(-.031 50 "Seats Won by Democrats (% of total, 0=50%)", size(huge) ) 
						text(.15 50 "`dashes'", orientation(vertical) color(gs10) ) 
						text(.30 68 "Democratic Control", color(gs10) size(vlarge) )
						text(.30 32 "Republican Control", color(gs10) size(vlarge)  )	`mes`r''
						ytitle("Fraction of Outcomes where" "Democrats Gained by at least 5%", size(huge))
						;
	#delimit cr
	
	
								
	restore
}
					
graph combine g0 g1, graphregion(color(white) fcolor(white) ) ysize(2)
graph export "graphs/new/manipulate/how_won.pdf", replace
graph drop g0 g1		

			


			
			
/******************************************************
	Figure A3:
******************************************************/


/*********
Incumbent Exit
**********/
use "dta/stateleg/compete_lh.dta", clear

//Outcome: indicator for whether a sitting lower house legislator does not compete
gen inc_exit		= (1 - competed_lh) if holdoffice_lh

//Unit of clustering (for standard errors)
egen clust = group(state_id year_redistrict)

keep if sample == 1


local run lagdemhs2
local cond1 republican==1
local cond2 (democrat==1 | republican==1)

keep if abs(`run') < 18 & !mi(`run')

local ytitle1 Estimate [Close] X [High-Stakes Elections] (95% CI)

cap postclose estimates
tempfile estimates
postfile estimates c bw b se nclust using `estimates'

foreach c in 1 2 {
	foreach bw of numlist 3(.1)12 {
		gen close = abs(`run') < `bw' if !mi(`run')
		
		reg inc_exit c.close##c.red_elect if `cond`c'', cluster(clust)
		
		local b 		= _b[c.close#c.red_elect]
		local se		= _se[c.close#c.red_elect]
		local nclust	= e(N_clust)
		
		post estimates (`c') (`bw') (`b') (`se') (`nclust')
		
		drop close
	}
}



postclose estimates
	
use `estimates', clear

gen bl = b - invt(`nclust'-1, .975)*se
gen bu = b + invt(`nclust'-1, .975)*se

local title1 "Republicans"
local title2 "Democrats"

foreach p in 1 2 {
	local estcol gs8
	#delimit;
	scatter b bl bu bw if c == `p', sort(bw) connect(direct direct direct) lp(solid dash dash) 
						lc(`estcol' `estcol' `estcol') mc(`estcol' `estcol' `estcol') 
						ms(O i i) msize(small)  xlabel(3(3)12, labsize(vlarge) ) title("`title`p''", size(huge))
						ylabel(-.1(.05).05, labsize(vlarge) ) yline(0, lc(black) )
						graphregion(color(white)) xtitle("Window for 'Closeness'", size(huge)) legend(off)
						ytitle("`ytitle`p''", size(huge)) name(ex`p')
						
			;
	#delimit cr
}

graph combine ex1 ex2, graphregion(color(white) fcolor(white) ) ysize(2) rows(1) name(ex) title("Incumbent Exit Rate", size(huge) )
graph drop ex1 ex2



/*********
Campaign Receipts
**********/

use "dta/stateleg/partisan_balance_lh.dta", clear


merge m:1 statename using "dta/statecode_crosswalk.dta"
drop if _m != 3
drop _m

merge 1:m stateabbrev election_year using "dta/stateleg/candidate_funds_lh.dta"
keep if _m == 3
keep if sample == 1



//Unit of clustering (for standard errors)
egen clust = group(state_id year_redistrict)



local run lagdemhs2
local cond1 party == "200"
local cond2 party == "100"
local out totalreceipts

keep if abs(`run') < 18 & !mi(`run')


cap postclose estimates
tempfile estimates
postfile estimates c bw b se nclust using `estimates'

foreach c in 1 2 {
	foreach bw of numlist 3(.1)12 {
		gen close = abs(`run') < `bw' if !mi(`run')
		
		reg `out' c.close##c.red_elect if `cond`c'', cluster(clust)
		
		local b 		= _b[c.close#c.red_elect]
		local se		= _se[c.close#c.red_elect]
		local nclust	= e(N_clust)
		
		post estimates (`c') (`bw') (`b') (`se') (`nclust')
		
		drop close
	}
}



postclose estimates
	
use `estimates', clear

gen bl = b - invt(`nclust'-1, .975)*se
gen bu = b + invt(`nclust'-1, .975)*se

local title1 "Republicans"
local title2 "Democrats"

foreach p in 1 2 {
	local estcol gs8
	#delimit;
	scatter b bl bu bw if c == `p', sort(bw) connect(direct direct direct) lp(solid dash dash) 
						lc(`estcol' `estcol' `estcol') mc(`estcol' `estcol' `estcol') 
						ms(O i i) msize(small)  xlabel(3(3)12, labsize(vlarge)) title("`title`p''", size(huge))
						yline(0, lc(black) ) ylabel(-60000(30000)60000, labsize(vlarge))
						graphregion(color(white)) xtitle("Window for 'Closeness'", size(huge)) legend(off)
						ytitle("", size(huge)) name(g`p')
						
			;
	#delimit cr
}

graph combine g1 g2, graphregion(color(white) fcolor(white) ) ysize(2) rows(1) name(finance) title("Total Campaign Receipts", size(huge))
graph drop g1 g2



/*********
Combine Everything
**********/

graph combine ex finance , graphregion(color(white) fcolor(white) ) ysize(2) rows(1)
graph drop ex finance 

graph export "graphs/new/manipulate/highstakesXclose.pdf", replace




/******************************************************
	Figure A4:
******************************************************/

use "dta/stateleg/candidate_funds_lh.dta", clear
rename election_year merge_year
tempfile funds
save `funds'




use "dta/stateleg/partisan_balance_lh.dta", clear



merge m:1 statename using "dta/statecode_crosswalk.dta"
drop if _m != 3
drop _m

gen merge_year = election_year
replace merge_year = election_year + 1 if mod(election_year, 2 ) == 1

drop if merge_year < 1990

drop if statename == "Mississippi" & merge_year <= 1992

merge 1:m stateabbrev merge_year using `funds'
keep if _m == 3
keep if sample == 1

gen dem = party == "100"



keep if incumchall == "I"

gen anycontrib = totalpccontribs > 0 if totalpccontribs < .
collapse (p25) totalpccontribs_l=totalpccontribs (p75) totalpccontribs_h=totalpccontribs (mean) anycontrib, by(statename election_year red_elect party lagdemhs2)

gen gap = totalpccontribs_h-totalpccontribs_l

//twoway (lpoly totalpccontribs_l lagdemhs2) (lpoly totalpccontribs_h lagdemhs2)

keep if abs(lagdemhs2) < 18

//twoway (lpoly anycontrib lagdemhs2 if red_elect == 0 & party == "100") (lpoly anycontrib lagdemhs2 if red_elect == 1 & party == "100")

#delimit;
twoway 	(lpoly gap lagdemhs2 if red_elect == 0 & party == "100", lp(dash) lc(gs8)) 
		(lpoly gap lagdemhs2 if red_elect == 1 & party == "100", lp(solid) lc(black))
		(scatteri 18000 -13 "" 18000 -10 "${redel}", connect(direct) lp(solid) lc(black) ms(i) mlabcolor(black)  mlabsize(medlarge) ) 
		(scatteri 16500 -13 "" 16500 -10 "${nonel}", connect(direct) lp(dash) lc(gs8) ms(i) mlabcolor(gs8) mlabsize(medlarge)   ) 
		,
		graphregion(color(white)) legend(off) graphregion(color(white)) 
			xtitle(${runlabinc}, size(large) ) ytitle("Average Within-State" "Inter-Quartile Range", size(large) )
			ylabel(0(5000)20000)
			;
#delimit cr


graph export "graphs/new/appendix/sampdef/finance/strategy_concentrate.pdf", replace




/******************************************************
	Figure A5:
******************************************************/
local run lev_demhs2
local bw 12
local out lagdemcon
local deg 1
local binsize 1

use "dta/stateleg/partisan_balance_lh.dta", clear

//Cluster (for standard errors)
egen clust = group(year_redistrict state_id)

//Indicator for control of the assembly
gen control = (`run' >= 0) if !mi(`run')

//Restrict to bandwidth
keep if abs(`run') < `bw'

//Generate control function
forvalues p=1/`deg' {
	gen poly`p' = `run'^`p'
}

keep if sample == 1

local title_0 "${nonel}"
local title_1 "${redel}"

local arrow_0 ""
local arrow_1 `"(scatteri .9 -4.5 "Colorado 2010" 1 -1 "", mlabsize(medlarge) ms(i) connect(direct) lc(red) mlabcolor(red) mlabposition(9))"'

cap graph drop  _all

foreach redind in 0 1 {
	preserve

	keep if red_election == `redind'

	//Run regression on micro data
	reg `out' poly* control c.control#c.poly* , cluster(clust)

	//Size of discontinuity and standard error
	local b 	= string( _b[control], "%9.3f" )
	local se 	= string( _se[control], "%9.3f" )

	//Round to construct bins
	gen bin = `run' - mod(`run',`binsize')

	//Take bin averages (and counts)
	gen nonmi = e(sample)
	br statename election_year bin `run' lagdemcon if abs(bin)<3
	sort bin
	collapse `out' (sum)nobs=nonmi, by(bin)

	//Recenter the running variable on the midpoints of the bins
	gen `run' 					= bin+`binsize'/2
	gen control					= `run' > 0


	forvalues p=1/`deg' {
		gen poly`p' = `run'^`p'
	}
	predict pred
	

		#delimit;
	twoway 
	(scatteri 	.05 -10 "Republican Control"
					.05 1 "Democratic Control", ms(i) mlabsize(medlarge) mlabcolor(gs10) )
	
	(scatter `out' `run' `useweight', msize(3) mc(navy) )				//Dots
	(line pred `run' if control)  				//Fit: Democratic control
	(line pred `run' if !control) 				//Fit: Republican control
	`arrow_`redind''
	,
	text(.3 3 "Discontinuity", size(large) )  text(.3 8 "`b'" "(`se')", size(large) ) 
	graphregion(color(white)) legend(off) 
	xtitle("Seats Won by Democrats ({bf:Current} Election)" "Level, 0 = Threshold for Majority" , size(vlarge))
	ytitle(${xlabmaj}, size(vlarge) ) ylabel(0 (.2) 1)
	title(" `title_`redind'' ", size(vlarge)) name(g`redind') xline(0, lc(gs14) lp(dash) )
	;
	#delimit cr
	
	restore
}


graph combine g0 g1, graphregion(color(white) fcolor(white) ) ysize(3)
graph export "graphs/new/appendix/discrete_runvar_bin1.pdf", replace
graph drop g0 g1





/******************************************************
	Figure A6:
******************************************************/

local run demhs2
local bw 18
local out lagdemcon
local deg 1
local binsize 2

use "dta/stateleg/partisan_balance_lh.dta", clear

drop if demhs2 == 0

//Cluster (for standard errors)
egen clust = group(year_redistrict state_id)

//Indicator for control of the assembly
gen control = (`run' >= 0) if !mi(`run')

//Restrict to bandwidth
keep if abs(`run') < `bw'

//Generate control function
forvalues p=1/`deg' {
	gen poly`p' = `run'^`p'
}

keep if sample == 1

local title_0 "${nonel}"
local title_1 "${redel}"

cap graph drop  _all

pause off
foreach redind in 0 1 {
	preserve

	keep if red_election == `redind'

	//Run regression on micro data
	reg `out' poly* control c.control#c.poly* , cluster(clust)

	//Size of discontinuity and standard error
	local b 	= string( _b[control], "%9.3f" )
	local se 	= string( _se[control], "%9.3f" )

	//Round to construct bins
	gen bin = `run' - mod(`run',`binsize')
	replace bin = bin+`binsize'/2
	
	//Take bin averages (and counts)
	gen nonmi = e(sample)

	
	collapse `out' (sum)nobs=nonmi, by(bin)

	pause
	//Recenter the running variable on the midpoints of the bins
	//gen `run' 					= bin+`binsize'/2
	gen `run' 					= bin
	gen control					= `run' > 0


	forvalues p=1/`deg' {
		gen poly`p' = `run'^`p'
	}
	predict pred

	#delimit;
	twoway 
	(scatteri 	-.02 -19 "Republican Control"
					-.02 1 "Democratic Control", ms(i) mlabsize(large) mlabcolor(gs10) )
	(scatter `out' `run' ${useweight}, msize(3) mc(navy) )				//Dots
	(line pred `run' if control)  				//Fit: Republican control
	(line pred `run' if !control) 				//Fit: Democratic control
	,
	text(.9 -14.5 "Discontinuity:", size(large) )  text(.9 -4 "`b'" "(`se')", size(large) ) 
	graphregion(color(white)) legend(off) 
	xtitle(${runlabdem}, size(vlarge) )
	ytitle(${xlabmaj}, size(vlarge) ) yscale( range(-0.05 1) ) ylabel(0 (.2) 1)
	title(" `title_`redind'' ", size(vlarge) ) name(g`redind') xline(0, lc(gs11) lp(dash) )
	;
	#delimit cr
	
	restore
}


graph combine g0 g1, graphregion(color(white) fcolor(white) ) ysize(3)
graph export "graphs/new/appendix/revisions/minor/drop_zeros.pdf", replace
graph drop g0 g1







/******************************************************
	Figure A7:
******************************************************/

local title_0 "${nonel}"
local title_1 "${redel}"


foreach redind in 0 1 {
	cap postclose rdest
	tempfile rdest
	postfile rdest bw b se nclust using `rdest'

	foreach bw of numlist 22(-.5)4 {
		local run demhs2
		local out lagdemcon
		local deg 1



		use "dta/stateleg/partisan_balance_lh.dta", clear

		//Cluster (for standard errors)
		egen clust = group(year_redistrict state_id)

		//Indicator for control of the assembly
		gen control = (`run' >= 0) if !mi(`run')

		//Restrict to bandwidth
		keep if abs(`run') < `bw'

		//Generate control function
		forvalues p=1/`deg' {
			gen poly`p' = `run'^`p'
		}

		keep if sample == 1
		
		keep if red_election == `redind'

		//Run regression on micro data
		//reg `out' poly* control c.control#c.poly* , cluster(clust)
		rdrobust `out' `run', vce( cluster clust) h(`bw')
		
		local b 		= e(tau_cl)
		local se		= e(se_tau_cl)
		
		egen tag = tag(clust)
		count if tag
		local nclust	= r(N)
		
		post rdest (`bw') (`b') (`se') (`nclust')

		
	}

	postclose rdest

	use `rdest', clear

	gen bl = b - invt(nclust-1, .975)*se
	gen bu = b + invt(nclust-1, .975)*se

	local estcol gs8
	#delimit;
	scatter b bl bu bw, sort(bw) connect(direct direct direct) lp(solid dash dash) 
						lc(`estcol' `estcol' `estcol') mc(`estcol' `estcol' `estcol') 
						ms(O i i) msize(small) ylabel(-.5(.5)2, labsize(large) )
						xlabel(4(6)22, labsize(large))
						 yline(0, lc(black) ) name(g`redind')
						graphregion(color(white)) xtitle("Bandwidth", size(huge)) legend(off)
						ytitle("Discontinuity (95% CI) ", size(huge)) title(" `title_`redind'' ", size(huge))
						
			;
	#delimit cr
}

graph combine g0 g1, graphregion(color(white) fcolor(white) ) ysize(3)
cap mkdir "graphs/new/appendix/revisions/minor"
graph export "graphs/new/appendix/revisions/minor/triangle_kernel.pdf", replace
graph drop g0 g1









/******************************************************
	Figure A8:
******************************************************/


use "dta/stateleg/partisan_balance_lh.dta", clear


keep if sample == 1

keep if abs(demhs2) < 18 

bysort red_election lagdemcon: gen tmp = _N
gen dens = 1/tmp

#delimit;
binplot dens if abs(demhs2) < 18 & red_election == 1 & lagdemcon == 0, x(demhs2) bw(3) stat(sum) lineone linebreak
			opt(`"  name(g1) xline(0, lp(dash) lc(gs10) ) ytitle("Fraction of Observations", size(large) )  ylabel(0(.05).2) xlabel(, labsize(medlarge))
			xtitle(${runlabdem}, size(large) ) title("Republicans Held Majority [${redel}]") legend(off) "')
			;
			
binplot dens if abs(demhs2) < 18 & red_election == 1 & lagdemcon == 1, x(demhs2) bw(3) stat(sum) lineone linebreak
			opt(`"  name(g2) xline(0, lp(dash) lc(gs10) ) ytitle("Fraction of Observations", size(large) )  ylabel(0(.05).2) xlabel(, labsize(medlarge))
			xtitle(${runlabdem}, size(large) ) title("Democrats Held Majority [${redel}]") legend(off) "')
			;
			
binplot dens if abs(demhs2) < 18 & red_election == 0 & lagdemcon == 0, x(demhs2) bw(3) stat(sum) lineone linebreak
			opt(`"  name(g3) xline(0, lp(dash) lc(gs10) ) ytitle("Fraction of Observations", size(large) ) ylabel(0(.05).2)  xlabel(, labsize(medlarge))
			xtitle(${runlabdem}, size(large) ) title("Republicans Held Majority [${nonel}]") legend(off) "')
			;
			
binplot dens if abs(demhs2) < 18 & red_election == 0 & lagdemcon == 1, x(demhs2) bw(3) stat(sum) lineone linebreak
			opt(`"  name(g4) xline(0, lp(dash) lc(gs10) ) ytitle("Fraction of Observations", size(large) ) ylabel(0(.05).2) xlabel(, labsize(medlarge))
			xtitle(${runlabdem}, size(large) ) title("Democrats Held Majority [${nonel}]") legend(off) "')
			;
			
#delimit cr

graph combine g3 g1 g4 g2 , graphregion(color(white) fcolor(white) ) ysize(3)
graph export "graphs/new/appendix/conditional_den.pdf", replace
graph drop g1 g3 g2 g4







/******************************************************
	Figure A9:
******************************************************/

local run demhs2
local bw 18
local out lagreddemcon
local deg 1
local binsize 2

use "dta/stateleg/partisan_balance_lh.dta", clear

//Cluster (for standard errors)
egen clust = group(year_redistrict state_id)

//Indicator for control of the assembly
gen control = (`run' >= 0) if !mi(`run')

//Generate control function
forvalues p=1/`deg' {
	gen poly`p' = `run'^`p'
}

keep if sample == 1

local title_0 "${nonel}"
local title_1 "${redel}"

cap graph drop  _all


keep if red_election == 1

sort state_id year
by state_id: gen elid2 = _n
xtset state_id elid2
gen lagreddemcon = l.demcon
drop if mi(`out')


preserve

//Restrict to bandwidth
keep if abs(`run') < `bw'


//Run regression on micro data
reg `out' poly* control c.control#c.poly* , cluster(clust)

//Size of discontinuity and standard error
local b 	= string( _b[control], "%9.3f" )
local se 	= string( _se[control], "%9.3f" )

//Round to construct bins
gen bin = `run' - mod(`run',`binsize')

//Take bin averages (and counts)
gen nonmi = e(sample)
collapse `out' (sum)nobs=nonmi, by(bin)

//Recenter the running variable on the midpoints of the bins
gen `run' 					= bin+`binsize'/2
gen control					= `run' > 0


forvalues p=1/`deg' {
	gen poly`p' = `run'^`p'
}
predict pred

#delimit;
twoway 
(scatteri 	.05 -14.5 "Republican Control"
				.05 1 "Democratic Control", ms(i) mlabsize(medlarge) mlabcolor(gs10) )
(scatter `out' `run' ${useweight}, msize(3) mc(navy) )				//Dots
(line pred `run' if control)  				//Fit: Republican control
(line pred `run' if !control) 				//Fit: Democratic control
,
text(.9 -14 "Discontinuity:", size(medlarge) )  text(.9 -7 "`b'" "(`se')", size(medlarge) ) 
graphregion(color(white)) legend(off) 
xtitle("Seats Won by Democrats, Current High-Stakes Election" "As % of total, relative to 50% threshold" , size(large) )
ytitle("Probability Democrats Won a Majority" "in Previous High-Stakes Election", size(large) ) ylabel(0 (.2) 1)
title("") xline(0, lc(gs11) lp(dash) )
;
#delimit cr

restore
		
graph export "graphs/new/appendix/prior_highstakes.pdf", replace



/******************************************************
	Figure A10 & A11:
******************************************************/

cap postclose rdest
tempfile rdest
postfile rdest eltype binsize bw b se using `rdest'

foreach eltype in 0 1 {
	foreach bw of numlist 8(1)15 {
		foreach binsize of numlist .75 1 2 3 4 {
			use "dta/stateleg/partisan_balance_lh.dta", clear

			keep if sample == 1

			//It's not clear how to code the "incumbent" in these cases, so we drop them
			drop if (l.hs_ind_elect > 0 & l.hs_ind_elect < .) | (hs_ind_elect > 0 & hs_ind_elect < .)


			gen incshare = 100 * ( hs_dem_elect - ceil(.5* hs_tot_elect) ) / hs_tot_elect if lagdemcon == 1
			replace incshare = 100 * ( hs_rep_elect - ceil(.5* hs_tot_elect) ) / hs_tot_elect if lagdemcon == 0


			keep if red_elect == `eltype'

			DCdensity incshare, breakpoint(0) generate(Xj Yj r0 fhat se_fhat) nograph b(`binsize') h(`bw')

			local b 		= r(theta)
			local se		= r(se)
			
			post rdest (`eltype') (`binsize') (`bw') (`b') (`se') 
		}
		
	}
}
postclose rdest

use `rdest', clear

gen bl = b - invnormal(.95)*se
gen bu = b + invnormal(.95)*se


local title_0 "${nonel}"
local title_1 "${redel}"

local graphlist ""
local count 0
foreach binsize of numlist .75 1 2 3 4 {
	foreach eltype in 0 1 {
		local ++count
		local graphlist "`graphlist' g`count'"
		
		local estcol gs8
		
		if `binsize' == .75 | `binsize' == 3 {
			local titleadd `""`title_`eltype''" "Bin Size = `binsize'""'
		}
		else {
			local titleadd `""Bin Size = `binsize'""'
		}
		#delimit;
		scatter b bl bu bw if eltype == `eltype' & binsize == `binsize', sort(bw) connect(direct direct direct) lp(solid dash dash) 
							lc(`estcol' `estcol' `estcol') mc(`estcol' `estcol' `estcol') 
							ms(o p p)  xlabel(8(1)15) ylabel(-.5(1.5)4)
							 yline(0, lc(black) ) name(g`count')
							graphregion(color(white)) xtitle("Bandwidth", size(medlarge)) legend(off)
							ytitle("RD Estimate (90% CI) ", size(medlarge)) title(`titleadd')
							
				;
		#delimit cr
	}
}


graph combine g1 g2 g3 g4 g5 g6, ysize(6) graphregion(color(white) fcolor(white)) cols(2)
graph export "graphs/new/appendix/mccrary_binbw1.pdf", replace

graph combine g7 g8 g9 g10, ysize(4) graphregion(color(white) fcolor(white)) cols(2)
graph export "graphs/new/appendix/mccrary_binbw2.pdf", replace

graph drop `graphlist'




/******************************************************
	Figure A12:
******************************************************/

local dosamptest = 1

if "`dosamptest'" == "1" {


	local bw 18
	local out lagdemcon
	local deg 1
	local binsize 2
	local run demhs2

	use "dta/stateleg/partisan_balance_lh.dta", clear



	//Cluster (for standard errors)
	egen clust = group(year_redistrict state_id)

	//Indicator for control of the assembly
	gen control = (`run' >= 0) if !mi(`run')

	//Restrict to bandwidth
	keep if abs(`run') < `bw'

	//Generate control function
	forvalues p=1/`deg' {
		gen poly`p' = `run'^`p'
	}
	
	keep if sample == 1
	keep if !mi(`out')

	reg `out' poly* control c.control#c.poly* if red_elect == 1, cluster(clust)
	local sampsize = e(N)
	local coef 		= _b[control]
	local coefse 	= _se[control]

	keep if red_elect == 0
	reg `out' poly* control c.control#c.poly*, cluster(clust)
	keep if e(sample)

	cap postclose rdest
	tempfile rdest
	postfile rdest rep b se nclust using `rdest'
	
	
	
	
	global seedtmp = c(seed)
	set seed 2750

	forvalues rep = 1/2000 {
		quietly {
			gen double draw = runiform()
			sort draw
			gen obscount = _n
			//gen insamp = obscount <= `sampsize'
			gen insamp = draw <= `sampsize'/_N
			
			/*
			Note: we do not cluster by state-redistricting year because there
			is only one obs per cluster in the actual set of high-stakes elections.
			
			If we clustered here it would bias the simulated t-stats towards
			0 and make the actual estimate look better than it really is.
			*/
			reg `out' poly* control c.control#c.poly* if insamp , robust
			
			local b 		= _b[control]
			local se		= _se[control]
			local nclust	= e(N_clust)
			
			post rdest (`rep') (`b') (`se') (`nclust')
			drop insamp draw obscount
		}
	}


	postclose rdest

	use `rdest', clear

	gen abst = abs(b/se) 
	gen sig5 = abst > invt(`sampsize'-1,.975)
	tab sig5
	
	gen bigger 		= `coef' > b
	gen biggerabs	= abs(`coef'/`coefse') > abst
	
	
	tab bigger
	tab biggerabs
	

	hist abst
	
	hist b, xline(`coef', lp(dash) lc(red)) graphregion(color(white)) xtitle("Estimate") ///
				ytitle("Density") text(2.5 .50 "${redel}" "Estimate", color(red))

	graph export "graphs/new/appendix/smallsamp.pdf", replace

	set seed ${seedtmp}
}



/******************************************************
	Figure A13:
******************************************************/

local run demhs2
local bw 18
local out lagdemcon
local deg 2
local binsize 2

use "dta/stateleg/partisan_balance_lh.dta", clear

//Cluster (for standard errors)
egen clust = group(year_redistrict state_id)

//Indicator for control of the assembly
gen control = (`run' >= 0) if !mi(`run')

//Restrict to bandwidth
keep if abs(`run') < `bw'

//Generate control function
forvalues p=1/`deg' {
	gen poly`p' = `run'^`p'
}

keep if sample == 1

local title_0 "${nonel}"
local title_1 "${redel}"

cap graph drop  _all

pause off
foreach redind in 0 1 {
	preserve

	keep if red_election == `redind'

	//Run regression on micro data
	reg `out' poly* control c.control#c.poly* , cluster(clust)

	//Size of discontinuity and standard error
	local b 	= string( _b[control], "%9.3f" )
	local se 	= string( _se[control], "%9.3f" )

	//Round to construct bins
	gen bin = `run' - mod(`run',`binsize')
	replace bin = bin+`binsize'/2
	
	//Take bin averages (and counts)
	gen nonmi = e(sample)
	
	collapse `out' (sum)nobs=nonmi, by(bin)

	pause
	//Recenter the running variable on the midpoints of the bins
	//gen `run' 					= bin+`binsize'/2
	gen `run' 					= bin
	gen control					= `run' > 0


	forvalues p=1/`deg' {
		gen poly`p' = `run'^`p'
	}
	predict pred

	#delimit;
	twoway 
	(scatteri 	-.02 -19 "Republican Control"
					-.02 1 "Democratic Control", ms(i) mlabsize(large) mlabcolor(gs10) )
	(scatter `out' `run' ${useweight}, msize(3) mc(navy) )				//Dots
	(qfit pred `run' if control)  				//Fit: Republican control
	(qfit pred `run' if !control) 				//Fit: Democratic control
	,
	text(.9 -14.5 "Discontinuity:", size(large) )  text(.9 -4 "`b'" "(`se')", size(large) ) 
	graphregion(color(white)) legend(off) 
	xtitle(${runlabdem}, size(vlarge) )
	ytitle(${xlabmaj}, size(vlarge) ) yscale( range(-0.05 1) ) ylabel(0 (.2) 1)
	title(" `title_`redind'' ", size(vlarge) ) name(g`redind') xline(0, lc(gs11) lp(dash) )
	;
	#delimit cr
	
	restore
}


graph combine g0 g1, graphregion(color(white) fcolor(white) ) ysize(3)
graph export "graphs/new/manipulate/incumbency_order2poly.pdf", replace
graph drop g0 g1

	
	
	
		
/******************************************************
	Figure A14:
******************************************************/

local run demhs2
local bw 18
local out lagdemcon
local deg 1
local binsize 2

use "dta/stateleg/partisan_balance_lh.dta", clear



//Cluster (for standard errors)
egen clust = group(year_redistrict state_id)

//Indicator for control of the assembly
gen control = (`run' >= 0) if !mi(`run')

//Restrict to bandwidth
keep if abs(`run') < `bw'

//Generate control function
forvalues p=1/`deg' {
	gen poly`p' = `run'^`p'
}

keep if sample == 1

local title_0 "${nonel}"
local title_1 "${redel}"

cap graph drop  _all

pause off
foreach redind in 0 1 {
	preserve

	keep if red_election == `redind'
	keep if election_year > 1966

	//Run regression on micro data
	reg `out' poly* control c.control#c.poly* , cluster(clust)

	//Size of discontinuity and standard error
	local b 	= string( _b[control], "%9.3f" )
	local se 	= string( _se[control], "%9.3f" )

	//Round to construct bins
	gen bin = `run' - mod(`run',`binsize')
	replace bin = bin+`binsize'/2
	
	//Take bin averages (and counts)
	gen nonmi = e(sample)
	br `out' bin `run' statename election_year
	sort bin
	pause
	#d;
	twoway (hist bin, width(2) start(-18) xlabel(-17 -13 -9 -5 -1 1 5 9 13 17) freq)
	(scatteri 0 0 50 0, c(l) lp(-) lc(red) m(i)),
	graphregion(color(white))
	ytitle("Number of State-Election Years in Each Bin")
	xtitle("As % of total, relative to 50% threshold")
	ylabel(0(10)50)
	title(" `title_`redind'' ", size(vlarge) ) name(hist`redind')
	legend(off);
	#d cr
	pause
	
	collapse `out' (sum)nobs=nonmi, by(bin)

	pause
	//Recenter the running variable on the midpoints of the bins
	//gen `run' 					= bin+`binsize'/2
	gen `run' 					= bin
	gen control					= `run' > 0


	forvalues p=1/`deg' {
		gen poly`p' = `run'^`p'
	}
	predict pred

	#delimit;
	twoway 
	(scatteri 	-.02 -19 "Republican Control"
					-.02 1 "Democratic Control", ms(i) mlabsize(large) mlabcolor(gs10) )
	(scatter `out' `run' ${useweight}, msize(3) mc(navy) )				//Dots
	(line pred `run' if control)  				//Fit: Republican control
	(line pred `run' if !control) 				//Fit: Democratic control
	,
	text(.9 -14.5 "Discontinuity:", size(large) )  text(.9 -4 "`b'" "(`se')", size(large) ) 
	graphregion(color(white)) legend(off) 
	xtitle(${runlabdem}, size(vlarge) )
	ytitle(${xlabmaj}, size(vlarge) ) yscale( range(-0.05 1) ) ylabel(0 (.2) 1)
	title(" `title_`redind'' ", size(vlarge) ) name(g`redind') xline(0, lc(gs11) lp(dash) )
	;
	#delimit cr
	
	restore
}

graph combine g0 g1, graphregion(color(white) fcolor(white) ) ysize(3)
graph export "graphs/new/appendix/sampdef/reynolds.pdf", replace
graph drop g0 g1






/******************************************************
	Figure A15: Secretary of State
******************************************************/
import excel using "raw data/state_code_abbrev.xlsx", clear firstrow sheet("stateabbrev")
tempfile abbrev
save `abbrev'

import delimited using "python/secstate/secstate.csv", clear
gen stateabbrev = substr(office,1,2)
replace stateabbrev = "NJ" if stateabbrev == "Se"

merge m:1 stateabbrev using `abbrev'

keep if _m == 3
drop _m

rename year election_year

duplicates drop party stateabbrev statename election_year, force
//Manually handle a few appointments
drop if incumbent == "Billy Joe Camp" & (election_year==1993 | election_year==1994)
drop if incumbent == "George Firestone" & (election_year==1987)
drop if incumbent == "Alan J. Dixon" & (election_year==1981 | election_year==1982)


/*****
Merge
******/
keep party stateabbrev statename election_year
rename party secparty
reshape wide secparty, i(stateabbrev) j(election_year)
reshape long secparty, i(stateabbrev) j(election_year)
sort stateabbrev election_year
replace secparty = secparty[_n-1] if mi(secparty) & stateabbrev==stateabbrev[_n-1]
merge 1:1 statename election_year using "dta/stateleg/partisan_balance_lh.dta"
drop if _m == 1
drop _m




/****
Run
****/
local run demhs2
local bw 18
local out secdem		
local deg 1
local binsize 2

sort fips eln
gen secdem = secparty == "D" /* This was scraped in such a way that the year 
								corresponds to year of service, not year elected; 
								so this is the secretary of state serving during
								the election */


//Cluster (for standard errors)
egen clust = group(year_redistrict state_id)

reg secdem lagdemcon, cluster(clust)

//Indicator for control of the assembly
gen control = (`run' >= 0) if !mi(`run')

//Restrict to bandwidth
keep if abs(`run') < `bw'

//Generate control function
forvalues p=1/`deg' {
	gen poly`p' = `run'^`p'
}

keep if sample == 1

local title_0 "${nonel}"
local title_1 "${redel}"

cap graph drop  _all

pause off
foreach redind in 0 1 {
	preserve

	keep if red_election == `redind'

	//Run regression on micro data
	reg `out' poly* control c.control#c.poly* , cluster(clust)

	//Size of discontinuity and standard error
	local b 	= string( _b[control], "%9.3f" )
	local se 	= string( _se[control], "%9.3f" )

	//Round to construct bins
	gen bin = `run' - mod(`run',`binsize')
	replace bin = bin+`binsize'/2
	
	//Take bin averages (and counts)
	gen nonmi = e(sample)
	
	collapse `out' (sum)nobs=nonmi, by(bin)

	pause
	//Recenter the running variable on the midpoints of the bins
	//gen `run' 					= bin+`binsize'/2
	gen `run' 					= bin
	gen control					= `run' > 0


	forvalues p=1/`deg' {
		gen poly`p' = `run'^`p'
	}
	predict pred

	#delimit;
	twoway 
	(scatteri 	-.02 -19 "Republican Control"
					-.02 1 "Democratic Control", ms(i) mlabsize(large) mlabcolor(gs10) )
	(scatter `out' `run' ${useweight}, msize(3) mc(navy) )				//Dots
	(line pred `run' if control)  				//Fit: Republican control
	(line pred `run' if !control) 				//Fit: Democratic control
	,
	text(.9 -14.5 "Discontinuity:", size(large) )  text(.9 -4 "`b'" "(`se')", size(large) ) 
	graphregion(color(white)) legend(off) 
	xtitle(${runlabdem}, size(vlarge) )
	ytitle("Probability Secretary of State" "Is a Democrat (During Election)", size(vlarge) ) yscale( range(-0.05 1) ) ylabel(0 (.2) 1)
	title(" `title_`redind'' ", size(vlarge) ) name(g`redind') xline(0, lc(gs11) lp(dash) )
	;
	#delimit cr
	
	restore
}


graph combine g0 g1, graphregion(color(white) fcolor(white) ) ysize(3)
cap mkdir "graphs/new/appendix/revisions/secstate"
graph export "graphs/new/appendix/revisions/secstate/sorting_test.pdf", replace

graph drop g0 g1





/******************************************************
	Figure A16:
******************************************************/


use "dta/stateleg/partisan_balance_uh.dta", clear
gen needed = ceil(.5* sen_tot_elect)
replace needed = needed+1 if mod(sen_tot_elect,2)==0
gen demsen2		= 100 * ( sen_dem_elect- needed ) / sen_tot_elect
gen lev_demsen2	= ( sen_dem_elect- needed )
drop demcon lagdemcon leaddemcon
gen demcon 		= demsen2 >= 0 if demsen2 < .

gen lagdemcon 	= l.demcon
gen leaddemcon	= f.demcon
gen lagdemsen2	= l.demsen2
gen leaddemsen2	= f.demsen2

label var demsen2 		"Seat margin of democrats in the lower chamber (%)"
label var lev_demsen2	"Seat margin of democrats in the lower chamber (Level)"
label var lagdemsen2 	"Seat margin of democrats in the lower chamber [previous election]"
label var leaddemsen2 	"Seat margin of democrats in the lower chamber [subsequent election]"

label var demcon 		"Indicator: democrats control the lower chamber"
label var lagdemcon 	"Indicator: democrats control the lower chamber [previous election]"
label var leaddemcon 	"Indicator: democrats control the lower chamber [subsequent election]"

	
	
/*************
 Upper Panels
**************/
tempfile original
save `original'

cap graph drop  _all

foreach bw of numlist 18(-3)12 {
	local run demsen2
	local out lagdemcon
	local deg 1
	local binsize 2



	//Cluster (for standard errors)
	egen clust = group(year_redistrict state_id)

	//Indicator for control of the assembly
	gen control = (`run' >= 0) if !mi(`run')

	//Restrict to bandwidth
	keep if abs(`run') < `bw'

	//Generate control function
	forvalues p=1/`deg' {
		gen poly`p' = `run'^`p'
	}

	keep if sample == 1

	local title_0 "${nonel}"
	local title_1 "${redel}"

	pause off
	foreach redind in 0 1 {
		preserve

		keep if red_election == `redind'

		//Run regression on micro data
		reg `out' poly* control c.control#c.poly* , cluster(clust)

		//Size of discontinuity and standard error
		local b 	= string( _b[control], "%9.3f" )
		local se 	= string( _se[control], "%9.3f" )

		//Round to construct bins
		gen bin = `run' - mod(`run',`binsize')
		replace bin = bin+`binsize'/2
		
		//Take bin averages (and counts)
		gen nonmi = e(sample)
		
		collapse `out' (sum)nobs=nonmi, by(bin)

		pause
		//Recenter the running variable on the midpoints of the bins
		//gen `run' 					= bin+`binsize'/2
		gen `run' 					= bin
		gen control					= `run' > 0


		forvalues p=1/`deg' {
			gen poly`p' = `run'^`p'
		}
		predict pred

		#delimit;
		twoway 
		(scatteri 	-.02 -19 "Republican Control"
						-.02 1 "Democratic Control", ms(i) mlabsize(large) mlabcolor(gs10) )
		(scatter `out' `run' ${useweight}, msize(3) mc(navy) )				//Dots
		(line pred `run' if control)  				//Fit: Republican control
		(line pred `run' if !control) 				//Fit: Democratic control
		,
		text(.9 -14.5 "Discontinuity:", size(large) )  text(.9 -4 "`b'" "(`se')", size(large) ) 
		graphregion(color(white)) legend(off) 
		xtitle("Seats Won by Democrats ({bf:Current} Election)" "As % of total, relative to 50%+1 threshold", size(vlarge) ) xlabel(-18(6)18)
		ytitle(${xlabmaj}, size(vlarge) ) yscale( range(-0.05 1) ) ylabel(0 (.2) 1)
		title(" `title_`redind'' ", size(vlarge) ) name(g`redind') xline(0, lc(gs11) lp(dash) )
		;
		#delimit cr
		
		restore
	}


	graph combine g0 g1, graphregion(color(white) fcolor(white) ) ysize(3) 
	cap mkdir "graphs/new/appendix/revisions/statesen"
	graph export "graphs/new/appendix/revisions/statesen/bw`bw'.pdf", replace
	graph drop g0 g1
	
	
	
	use `original', clear
}





/*************
 Bottom Panels
**************/
local title_0 "${nonel}"
local title_1 "${redel}"


foreach redind in 0 1 {
	cap postclose rdest
	tempfile rdest
	postfile rdest bw b se nclust using `rdest'

	foreach bw of numlist 22(-.5)4 {
		local run demsen2
		local out lagdemcon
		local deg 1


		use "dta/stateleg/partisan_balance_uh.dta", clear
		gen needed = ceil(.5* sen_tot_elect)
		replace needed = needed+1 if mod(sen_tot_elect,2)==0
		gen demsen2		= 100 * ( sen_dem_elect- needed ) / sen_tot_elect
		gen lev_demsen2	= ( sen_dem_elect- needed )
		drop demcon lagdemcon leaddemcon
		gen demcon 		= demsen2 >= 0 if demsen2 < .

		gen lagdemcon 	= l.demcon
		gen leaddemcon	= f.demcon
		gen lagdemsen2	= l.demsen2
		gen leaddemsen2	= f.demsen2

		label var demsen2 		"Seat margin of democrats in the lower chamber (%)"
		label var lev_demsen2	"Seat margin of democrats in the lower chamber (Level)"
		label var lagdemsen2 	"Seat margin of democrats in the lower chamber [previous election]"
		label var leaddemsen2 	"Seat margin of democrats in the lower chamber [subsequent election]"

		label var demcon 		"Indicator: democrats control the lower chamber"
		label var lagdemcon 	"Indicator: democrats control the lower chamber [previous election]"
		label var leaddemcon 	"Indicator: democrats control the lower chamber [subsequent election]"

			
		//Cluster (for standard errors)
		egen clust = group(year_redistrict state_id)

		//Indicator for control of the assembly
		gen control = (`run' >= 0) if !mi(`run')

		//Restrict to bandwidth
		keep if abs(`run') < `bw'

		//Generate control function
		forvalues p=1/`deg' {
			gen poly`p' = `run'^`p'
		}

		keep if sample == 1
		
		keep if red_election == `redind'

		//Run regression on micro data
		reg `out' poly* control c.control#c.poly* , cluster(clust)
		
		local b 		= _b[control]
		local se		= _se[control]
		local nclust	= e(N_clust)
		
		post rdest (`bw') (`b') (`se') (`nclust')

		
	}

	postclose rdest

	use `rdest', clear

	gen bl = b - invt(nclust-1, .975)*se
	gen bu = b + invt(nclust-1, .975)*se

	local estcol gs8
	#delimit;
	scatter b bl bu bw, sort(bw) connect(direct direct direct) lp(solid dash dash) 
						lc(`estcol' `estcol' `estcol') mc(`estcol' `estcol' `estcol') 
						ms(O i i) msize(small) ylabel(-.5(.5)2, labsize(large) )
						xlabel(4(6)22, labsize(large))
						 yline(0, lc(black) ) name(g`redind')
						graphregion(color(white)) xtitle("Bandwidth", size(huge)) legend(off)
						ytitle("Discontinuity (95% CI) ", size(huge)) title(" `title_`redind'' ", size(huge))
						
			;
	#delimit cr
}

graph combine g0 g1, graphregion(color(white) fcolor(white) ) ysize(3)
cap mkdir "graphs/new/appendix/revisions/statesen"
graph export "graphs/new/appendix/revisions/statesen/allbw.pdf", replace
graph drop g0 g1





/******************************************************
	Figure B1.A:
******************************************************/
global simseed XAA938e01445b7e133694c1928c8f6f6552ff2fb9992494ec2c0adeb70fac07411bbc3b9efcc4c325e468d1971414a1a930f1709ff9e76f1a6d7d8e48e0ca5d921c5d415ccde2294fa6f2b167ba5a01f2b01eca69aea82bb723ceab2a6fd9664a84712279c8a477405e93e98535fb8bad7713d9d093b61c3a5a7b7f1839a6b8b21b8bc06ce1e6779e3a807e2c7b27e86c32e14f2eb6cd41811d2a18d5915cc6dd3438cbe2b54c5765c8a7a44056322695d831be479a028df4adafe74ee798c582de9b5179540d61a159f7b3f997af98e04f7c4a6da9e8ab4bdcf3692a10c9746ed378aadbccfe26eeea69ea5a9da2955a002bbe7bb874924743437ca7e6e6bbfd690b7235ac1bf21cc1773528f08c1b3012de81d0b9d5443c88d62833f56fda8fbc26a9d86a00a9daea59d7040a2e84efa6a159691ef659f63b3b02ac3a97127ad0f68fec24d80810dbda203fbff334f0c581e44bd8e669285dfdf47bdf01f0be4e40471833a26a3c15ab9a0404620d75bc1d92daba837abfe22318f4974779750ce9f9ed587547d22d1c12291f03b2191fe1bae69a685fe425b53a658286d6d8402c00ee56c91d69dfa1f4afb96878c0454556e5666a4a8a3230bdcaf4a598e99c9b8c514c54954e9fb8813e52c9617a31dd7d31229afbd9fe4bc99ffdb1156802230100963f5fe68b277378e1dba53cdcc431238b867c9201d303c929902239cc843f5e9a7168409d68bb5509064a260ef92f3ad11ef2e101748ca4367a95ef96a6a38d3276433c5bfa75562f0b6c4eac1357288d98d2c8636e504948f7153f804bd3e5d17e556f0fd4569e0c2a975c5e57c63515abffd4694a1451e9da30537ff127d127806e8b580bd4afb7ff4a4e2658095e88ad3e33f8a1f431fa447be8b82f3964f4d06ddb3972b81f07bb3dfafcdf8d7297b3f3ef4cb887c0cbd7075f00be9a2341cd9d8bc1d580d4f0c09417a13e5111cc9084c3cc45960ff9e8c12c4ae4cdd9407f6468a16920fdbc0f61aa70d72873613c9f652459de59b427079e59d69d1763b771c35dd4099c0d52cd2e77cef78b8f8d98cc2ada8a55534dee8a6c0fdfc3a239d210ae523c49d35579f070c1fa8ae4325bd4d765c49f60ff9312951ca3df2fef1adb26eb8cc75a617e294392fc572d8332c3fb5d311d5f0aaaf00625b31f0c01c1074f169a4a8147bff0448bf588bd180a1294bd72135b03f2a3c42beab50688534be27d68d927cd47b8015306812987530be68edea7627505d02980f8900d385583e22fa8cc14617f7e931609f4af5b39b0231a3257ffd25dcabef36a801968e34994a1915d3986e5280fd06088ab95661dab7af5d391771b7dae4b5d9df78087ece5cee824b5aa0e002b0dd29938b58a762609dc1001ba3df482ff6bfcb9438f955c23cd5676dc78c7fac47fd85f0ec72f2c240d40d12bf2bf3f56849395c649edd06de3f3ccfb9337e24107a7148d3027f56b30a1524875fe06cd4fec861ada133b1750c3a451470b9b9fd75564c795458065f0c1a42db98b08ac62e12ef5b44efb4e8e4e211f0101b16ab5adf5fb1624a664cc08072358897a9581fce2fd43fb07a0617d2eb1044900c1a02cb00241557cd338e54343eb25a37c5086b1165b77a0da6bcff913dd68f7e423be04eea715b39190a1c9266b7f696a2b87faae9d702ae0fa6897c3ddc16b54e67224a38d6e3f5f2108c3d78d48e003a39c959999f1fd14823746c6a311a433b95b4330870569a8fccc21ae10f7bdf2532a5e742c61759ca18bd078aa7298f8236c98a6632d0290babebf80340f1923904e658ab1b863abfe24a46ccdf54c23adaa2d715bbb298f42a594d526a7cfbacd68be190a36938307b4b6afe7e7a2819ada6aa9149e608f4f296a7498c408ae96b27a8029d4b80bebfe34b0c2d254f08f666ad5977d3b621d9f4146cb7e22467e51a9cb64218231e5734426b266c9f86a6fc6d757c451489946059b2b45fdfb9352c0150504fe7b54e88b289766a947e963515f6f71c635e3298aaf07e51a9ba1627b0bc3e651689cd12ac23b238cf308f2ef21eebe40db2cbbd0309ddae80068d58ab9168d21048e0554c0fb61262ba49480fe10673a40312e1e605e797f6eaed6d6723f664499a4a5fb39c5af37868219c740003c0295c245ed91f6be3477d6c8cd4b2db5094caf0136acb13696ebabecf90220d88f5462b3671ea9bad4876b9a75deaf31722f8b0537c72350d3b156ab4ccdce0320f8dbbea81b0258bf6f1a4ecd0aef5998c7649b4ee3e37dd048e876f21167aab8eb18e7f86e10aa9acb1698189453f7066e769fbd34980674abbf19727e57544c9dffc9788c91a69f5866807c400704ae5acc0adeb01f065e074a5080a405e1f779ebc3aec55c75d0702335fa6c8cbe7dd252394fc2a6b55f4d5fd0e7131d4c3da6b34ae7e1f472d5219718e7a445a5efcbc546e29c1e891f373f771a4b9df2c1e7a3d8c6a2acc1643964608a2fd86833a0bcdaa85252c98e48ef6d712a3bf814787cd9b52b40cd3d0c1c14144994d0e4a544028cdd1d1663a9274133c39ab93aabf3be20e07c7bf9f2caba3063c8044fe43c1f88dee948483cbc4e3beff799998289f00502148224c291875e658fa6f8fe176307cda7fc92079170f0e143d377f17385ccb9b679d96e580d4980651cfb16379c475ca2f7f3194f5383a68def5230ca237cce96ef3be1b6eb64f35aa3f27df6119814e2d1ab1192d559e272ca1a6efb0a053cf5c7dff6d61adc3a39203d148dc1d0eefc59398061738274bf64220129addcf5c882ec903385efb53b86f06cc74e40d40272b51e4dd6abe59dd87738ad615ac3b7b518a88f8858f9f5de013095d70c7822171b3d90329a64b56c542f7e73c5c90284433789125ad404943f83df0cc1a38a2adc7e5f633f8f6f4531410281f68d01c2d5524fad2e392f3a94a3e9bdabcb8d107b37e020cf5e6532c11090b99c647b3ba82bcc20e70efd0c73208cb7a1f7b676b3f7c816c042628c0081bbd1fb09eb22d5ad506ebfd2cb74b80021cc6dc731418d4400ff825c78aa4000f14c2468ebe3b099588e80743e9fed1803b1d7f8063c364534c2580cf8e843f1daa7ddb278d7da1fcc5cc1038e597d4268c9316682c0f421c78877a9686a4f542292522c0b95f5903dfa7e9d640f1406d5d7dcb620f87bd17e158c3b5dd3a5047256f25613e812b441271edb89456b1a8f69e13d1777e1ffc6877606a9300290f80a88029dedac3e3774051ddef4b57b89c73b8f1808742d690cd485a85cc4996c5b6e1ef571ec9add5549d47ae767355b06cadb8adcbcb9416597cdd11c1017b410081a47a47c3f0656c56a308e7db29f57a6e784a35478b974b6a62a92641c26d9acba3516dd59d928220b15028184a5064736b4a7e69d05172e1712d8790c34e4f51e563573f4e70444218ffa0186f406c091d734fba17ee1a58c13fb3a8e9f573b18a9bced67eef170c763d76b22bcc3288027504845f3527486bb6be08f11815a83affe260001000001121eaa

//Functional form of the expenditure effectiveness function
	cap program drop hfunc
	program hfunc
		args input outname
		gen `outname' = (`input')^(1/2)*.5
		//gen `outname' = (`input')^(4/5)*.5
		//gen `outname' = (`input')^(1/5)*.5
	end

//Constructs a single counterfactual election
	cap program drop runsim
	program runsim
		args manip
		
			
		local nseats 251
		local nelections 200
		//local incadv .25 don't use this parameter anymore...
		local concentration 30
		local timeshocksd .2
	
		tempfile res
		cap postclose res
		postfile res win inc using `res'
	
		local majceil 	= ceil(`nseats'/2)
		local majfloor	= floor(`nseats'/2)
		forvalues i=1/`nelections' {
			quietly {
				clear
				set obs `nseats'
				
				gen aggdraw = `=rnormal()'
				gen incumbent = runiform() < normal(aggdraw)
				
				gen err 		= rnormal()*1
				gen timeshock	= `=(runiform()-.5)*`timeshocksd''
				gen a 			= normal(aggdraw + err)
				//gen a 			= normal(aggdraw + timeshock + err)
				
				sum a, detail
				gen abovemed = a >= r(p50)
				gen belowmed = a <= r(p50)
				gen x = 1 
				gen y = 1
				
				if "`manip'" == "1" {
					sort a
					replace x = sqrt((`nseats'+1-_n)/`majfloor') * `concentration' if _n > `majfloor'
					replace x = .2*x if _n <= `majfloor'
					
					replace y = sqrt((_n)/`majceil') * `concentration'  if _n <= `majceil'
					replace y = .2*y if _n > `majceil'
				}
				
	
				hfunc x hmaj
				hfunc y hmin
	
				gen p = (a*hmaj + timeshock) / (a*hmaj + (1-a)*hmin + timeshock)
	
				gen draw = runiform()
				gen majwin = draw < p 
				
				collapse (sum) majwin incumbent 
				
				sum majwin
				local majwin = r(mean)
				sum incumbent
				local incumbent = r(mean)
				post res (`majwin') (`incumbent')
			}
		}
	
		postclose res
		use `res', clear
	
	
		gen legsize = `nseats'
		gen demhs2 		= (win- ceil(.5*legsize) )/legsize * 100
		gen lagdemhs2 	= (inc-ceil(.5*legsize) )/legsize * 100
		gen difdemhs2	= demhs2-lagdemhs2
		gen lagdemcon	= lagdemhs2 >= 0
	end



// Simulation
set seed ${simseed}

local title_0 "Uniform Strategy"
local title_1 "Majority-Seeking Strategy"
 
foreach manip in 0 1 {
	runsim `manip'
	
	preserve
	local out 		lagdemcon
	local run 		demhs2
	local bw		18
	local binsize	2
	local deg 		1

	//Indicator for control of the assembly
	gen control = (`run' >= 0) if !mi(`run')

	//Restrict to bandwidth
	keep if abs(`run') < `bw'

	//Generate control function
	forvalues p=1/`deg' {
		gen poly`p' = `run'^`p'
	}


	//Run regression on micro data
	reg `out' poly* control c.control#c.poly* 

	//Size of discontinuity and standard error
	local b 	= string( _b[control], "%9.3f" )
	local se 	= string( _se[control], "%9.3f" )

	//Round to construct bins
	gen bin = `run' - mod(`run',`binsize')

	//Take bin averages (and counts)
	gen nonmi = e(sample)
	collapse `out' (sum)nobs=nonmi, by(bin)

	//Recenter the running variable on the midpoints of the bins
	gen `run' 					= bin+`binsize'/2
	gen control					= `run' > 0


	forvalues p=1/`deg' {
		gen poly`p' = `run'^`p'
	}
	predict pred

	#delimit;
	twoway 
	(scatter `out' `run' ${useweight}, msize(3) mc(navy) )				//Dots
	(line pred `run' if control)  				//Fit: Republican control
	(line pred `run' if !control) 				//Fit: Democratic control
	,
	text(.9 -14 "Discontinuity", size(medlarge) )  text(.9 -4 "`b'" "(`se')", size(medlarge) ) 
	graphregion(color(white)) legend(off) ylabel(0(.2)1)
	xtitle("Margin of Seats Won by Democrats (%)" , size(large) )
	ytitle("Probability Democrats Held" "Majority Before Election", size(large) ) 
	title(" `title_`manip'' ") xline(0, lc(gs14) lp(dash) )  name(g`manip')
	;
	#delimit cr

	restore
}

graph combine g0 g1, graphregion(color(white) fcolor(white) ) ysize(3)
cap mkdir "graphs/new/appendix/revisions"
cap mkdir "graphs/new/appendix/revisions/sim"

graph export "graphs/new/appendix/revisions/sim/example.pdf", replace

graph drop g0 g1




/******************************************************
	Figure B1.B:
******************************************************/
set seed ${simseed}

tempfile allsims
cap postclose allsims
postfile allsims manip i b se df using `allsims'
quietly {
	foreach manip in 0 1 {
		if `manip'==1{
			noisily di "======================Precise Control========================"
		}
		else {
			noisily di "=====================No Precise Control======================"
		}
		forvalues i=1/500 {
			if mod(`i',20)==0 {
				noisily di ".`i'"
			}
			else {
				noisily di "." _c
			}
			runsim `manip'
			
			local out 		lagdemcon
			local run 		demhs2
			local bw		18
			local binsize	2
			local deg 		1

			//Indicator for control of the assembly
			gen control = (`run' >= 0) if !mi(`run')

			//Restrict to bandwidth
			keep if abs(`run') < `bw'

			//Generate control function
			forvalues p=1/`deg' {
				gen poly`p' = `run'^`p'
			}


			//Run regression on micro data
			reg `out' poly* control c.control#c.poly* 

			//Size of discontinuity and standard error
			local b 	=  _b[control]
			local se 	=  _se[control]
			local df	= e(df_r)
			post allsims (`manip') (`i') (`b') (`se') (`df')
		}
	}

}

postclose allsims
use `allsims', clear
gen t = b/se

bysort manip: sum b, detail

twoway (kdensity b if manip == 0) (kdensity b if manip == 1), ///
	legend(label(1 "Uniform Strategy") label(2 "Majority-Seeking Strategy")) graphregion(color(white)) ///
	xtitle("Estimated Discontinuity") ytitle("Density") name(coef)
twoway (kdensity t if manip == 0) (kdensity t if manip == 1), ///
	legend(label(1 "Uniform Strategy") label(2 "Majority-Seeking Strategy")) graphregion(color(white)) ///
	xtitle("T-Stat of Estimate") ytitle("Density") name(tstat)
	
	
graph combine coef tstat, graphregion(color(white) fcolor(white) ) ysize(3)
graph export "graphs/new/appendix/revisions/sim/multisim.pdf", replace
graph drop coef tstat




